5

I am a starter in jQuery . How to find all the controls in a form using jQuery?

I know the code is like this

function submitValidator(){
   $("form :input").each(function(){ });

I want to access their Id's and need to apply regular expressions

Some of the text boxes are numeric remaining will be alphanumeric. Is there any method to sort them to apply regular expressions?

4

5 回答 5

6

You can add a new property data-charSet in HTML

<input type="text" id='amt' data-charSet='numeric'>

add which all controlles you want to add after the "form :"

function submitValidator(){
                   $("form :text, textarea").each(function(){         
                        var NumericOnly = "^[0-9]*$";
                        var svId = $(this).attr('id');
            if($(this).attr('data-charSet') == 'numericonly')
                    {
                         if(!$(this).val().match(NumericOnly)) { 
                            alert("numeric");
                            eval("$('#" + svId +"').focus();")
                            return false;
                            }
                    }
                    });
            }
于 2013-07-25T14:50:02.723 回答
2

It's jQuery, not j-query. Anyway...

You can do it like this:

$("form :input").each(function (index, element) { 
    var id = $(this).attr("id"); // returns the object ID
    var value = $(this).val(); // returns the object value
    // etc
});
于 2013-07-25T12:46:17.330 回答
1

use

function submitValidator() { 
   $("form :input").each(function(){ 
       var id = $(this).attr('id'); // here you got id
   });
} // here missed brace
于 2013-07-25T12:45:06.723 回答
0

you need not to get Id if you can get object

function submitValidator() { 
   $("form :input ,form textarea").each(function(){ 
    $(this).yourfunction();
   });
}

:input will only give you tags with input, textarea will be missed so need to add that as well

于 2013-07-25T12:47:33.083 回答
0

I think you want to do something like this:

$("form").find("input").each(function(){ 
   var currentElementsId = $(this).attr("id");
   if(currentElementsId.match(/^regex/)){
      //do something
   }
});

if you want to get more than only input elements inside the form tag, you can put multiple selectors in the find() function like this; find("input,select,textarea,.className,[type='valueOfAttributeType']") and obviously any other selectors

于 2013-07-25T12:47:42.077 回答