【问题标题】:Iterate through all form elements irrespective of their type遍历所有表单元素,无论其类型如何
【发布时间】:2013-02-04 09:10:47
【问题描述】:

我正忙于为我们的一位客户处理表单管理器。总体思路是为各个部门构建表单,我想创建一个微系统来处理表单的验证等,而无需重做太多工作。尽可能自动化。

我的第一个主要任务是,我想在单击提交按钮时遍历整个表单,并根据特定的凭据和验证规则在表单发送到服务器之前对其进行验证。我看过许多与获取表单中所有输入字段的示例相关的帖子,但我正在寻找一种解决方案,它将遍历整个表单及其内容,然后对所有表单元素(包括选择框、输入框、文本框等)。

我可以单独执行此操作,但我希望验证从上到下进行,因此如果第一个字段是示例选择,下一个是输入字段,它应该从上到下遍历表单,所以我可以据此输出错误。

// Sample code:
$(document).ready(function() {
    $("#main_submit").click(function() {
        // Select all of the form fields here and iterate through them ...
    });
});
<form name='test_form' method='POST' action=''>
    <div>
        <label for='title'>Title</label>
        <select name='title'>
            <option value=''>Please select ...</option>
            <option value='MR'>MR.</option>
        </select>
    </div>
    <div>
        <label for='full_name'>Full Name:</label>
        <input name='full_name' type='text' />
    </div>
    .....
</form>

【问题讨论】:

标签: javascript jquery


【解决方案1】:

使用 jQuery :input 选择器:

jQuery("form :input");

描述:选择所有输入、文本区域、选择和按钮元素。

http://api.jquery.com/input-selector/

【讨论】:

    【解决方案2】:

    试试这个:

    //loop through all input elements
    $("form :input").each(function(){
        var thevalue = $(this).val();//the value of the current input element
        var thename = $(this).attr('name');//input name
        var thetype = $(this).attr('type');//input type
    });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-04-15
      • 1970-01-01
      • 2020-04-14
      • 2014-05-31
      • 2015-02-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多