简体   繁体   中英

Find All the controls in a form using jQuery or javascript

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?

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;
                            }
                    }
                    });
            }

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
});

use

function submitValidator() { 
   $("form :input").each(function(){ 
       var id = $(this).attr('id'); // here you got id
   });
} // here missed brace

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM