【问题标题】:how to get all checkboxes from one of three forms?如何从三种形式之一中获取所有复选框?
【发布时间】:2016-04-20 14:03:09
【问题描述】:

我有三个表单,每个表单都有复选框和提交按钮。我需要通过单击此表单中的提交按钮来获取所有复选框名称或 ID。 还有另外两个。

function getCheckedBoxes(item) {
    var checkboxes = document.getElementsByName(item);
    var checkboxesChecked = [];
    // loop over them all
    for (var i=0; i<checkboxes.length; i++) {
        // And stick the checked ones onto an array...
        if (checkboxes[i].checked) {
            checkboxesChecked.push(checkboxes[i]);
        }
    }
    // Return the array if it is non-empty, or null
    console.log(checkboxes);
    return checkboxesChecked.length > 0 ? checkboxesChecked : null;
}

var inp = document.getElementsByName('send');
for(var i = 0; i < inp.length; i++){
    inp[i].addEventListener('click', function(e) {
        getCheckedBoxes("item");
        e.preventDefault();
    });
}

我的复选框示例

<form>
    <input id="check29" type="checkbox" name="item" value="29" />
    <input class="lab-btn" type="submit" value="ADD ALL" name="send">
</form>

【问题讨论】:

    标签: javascript forms checkbox


    【解决方案1】:

    您可以将表单作为参数传递给函数,然后使用 querySelectorAll 来获取具有所需名称的所有输入。

    首先,将事件处理程序更改为:

    inp[i].addEventListener('click', function(e) {
        getCheckedBoxes(this.form, "item");
        e.preventDefault();
    });
    

    然后函数本身来:

    function getCheckedBoxes(oForm, item) {
        var checkboxes = oForm.querySelectorAll('input[name="' + item + '"]');
        //...
    }
    

    【讨论】:

      【解决方案2】:

      要选择页面上的所有复选框,您可以使用:

      var checkboxes = document.querySelectorAll("input[type=checkbox]");
      
      // And for all checkboxes in a form:
      var checkboxesInForm = form.querySelectorAll("input[type=checkbox]");
      

      有关文档,请参阅 https://developer.mozilla.org/nl/docs/Web/API/Document/querySelectorAll

      这能回答你的问题吗?

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-07-08
        • 2016-03-17
        • 1970-01-01
        • 2011-04-19
        • 1970-01-01
        相关资源
        最近更新 更多