使用jQuery或javascript查找表单中的所有控件

时间:2013-07-25 12:42:27

标签: javascript jquery

我是jQuery的首发。如何使用jQuery查找表单中的所有控件?

我知道代码就像这样

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

我想访问他们的Id并需要应用正则表达式

某些文本框是数字,其余为字母数字。有没有方法可以对它们进行排序以应用正则表达式?

5 个答案:

答案 0 :(得分:6)

您可以在HTML中添加新属性data-charSet

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

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

答案 1 :(得分:2)

它是 jQuery ,而不是 jquery 。 总之...

你可以这样做:

$("form :input").each(function (index, element) { 
    var id = $(this).attr("id"); // returns the object ID
    var value = $(this).val(); // returns the object value
    // etc
});

答案 2 :(得分:1)

使用

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

答案 3 :(得分:0)

如果可以获得对象,则无需获取ID

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

:输入只会给你输入标签,textarea会丢失,所以需要添加

答案 4 :(得分:0)

我想你想做这样的事情:

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

如果你想获得的不只是form标签中的输入元素,你可以在find()函数中放置多个选择器,就像这样; find("input,select,textarea,.className,[type='valueOfAttributeType']")以及任何其他选择器