【问题标题】:Automatically get values of all element inside a div with jQuery使用jQuery自动获取div内所有元素的值
【发布时间】:2012-01-25 04:18:05
【问题描述】:

我有一个主 div,其中有很多输入文本和单选按钮。
像这样:

<div id="mainDiv">
   <input type="text" name="text-1" /> <br/>

   <input type="radio" name="radio-1" />Yes
   <input type="radio" name="radio-1" />No <br/>

   <input type="text" name="text-2" /> <br/>
   <input type="text" name="text-3" /> <br/>
</div>
<img src="img/img.gif" onclick="getAllValues();" />

我想在 jQuery 中定义函数 getAllValues() 以获取 mainDiv 中的所有值并将它们保存在一个字符串中。
有可能吗?

【问题讨论】:

标签: javascript jquery html forms


【解决方案1】:

要实现这一点,您可以选择所有表单字段并使用map() 从它们的值创建一个数组,可以根据它们的type 检索该数组。试试这个:

function getAllValues() {
    var inputValues = $('#mainDiv :input').map(function() {
        var type = $(this).prop("type");

        // checked radios/checkboxes
        if ((type == "checkbox" || type == "radio") && this.checked) { 
           return $(this).val();
        }
        // all other fields, except buttons
        else if (type != "button" && type != "submit") {
            return $(this).val();
        }
    })
    return inputValues.join(',');
}

if 语句可以在这里合并,但为了清楚起见,我将它们分开。

【讨论】:

  • 它适用于输入文本,但使用单选按钮时,我只会采用选定的值。谢谢罗里! ​​
  • type != "button" || type != "submit" 这不应该是&amp;&amp; 而不是|| 吗?否则你会捡起所有东西。
  • @JonWyatt 谢谢!你是对的 - 7.5 年来第一个注意到的人 :)
【解决方案2】:

试试这样的:

function getAllValues() {
  var allVal = '';
  $("#mainDiv > input").each(function() {
    allVal += '&' + $(this).attr('name') + '=' + $(this).val();
  });
  alert(allVal);
}

【讨论】:

    【解决方案3】:

    这是为您构建 JSON 字符串的解决方案。它获取文本字段、复选框和选择元素的值:

    function buildRequestStringData(form) {
        var select = form.find('select'),
            input = form.find('input'),
            requestString = '{';
        for (var i = 0; i < select.length; i++) {
            requestString += '"' + $(select[i]).attr('name') + '": "' +$(select[i]).val() + '",';
        }
        if (select.length > 0) {
            requestString = requestString.substring(0, requestString.length - 1);
        }
        for (var i = 0; i < input.length; i++) {
            if ($(input[i]).attr('type') !== 'checkbox') {
                requestString += '"' + $(input[i]).attr('name') + '":"' + $(input[i]).val() + '",';
            } else {
                if ($(input[i]).attr('checked')) {
                    requestString += '"' + $(input[i]).attr('name') +'":"' + $(input[i]).val() +'",';
                }
            }
        }
        if (input.length > 0) {
            requestString = requestString.substring(0, requestString.length - 1);
        }
        requestString += '}';
        return requestString;
    }
    

    你可以这样调用函数:

    buildRequestStringData($('#mainDiv'))
    

    结果http://jsfiddle.net/p7hbT/

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-01-25
      • 1970-01-01
      • 2013-05-19
      • 2013-01-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多