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

Find All the controls in a form using jQuery or javascript

本文关键字:控件 表单 jQuery javascript 查找 使用      更新时间:2023-09-26

我是jQuery的初学者。如何使用jQuery查找表单中的所有控件?

我知道代码是这样的

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

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

有些文本框是数字框,剩下的将是字母数字框。有什么方法可以对它们进行排序以应用正则表达式吗?

您可以在HTML 中添加新的属性数据charSet

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

在"表单:"之后添加要添加的所有控制器

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

这是jQuery,而不是j-query。无论如何

你可以这样做:

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

使用

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

如果可以获取对象,则不需要获取Id

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

:input只会给你带input的标签,文本区域会被错过,所以需要添加它。

我想你想做这样的事情:

$("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']")和任何其他选择器