循环遍历页面上所有选中的复选框,并将id拉入数组无法正常工作

时间:2015-03-05 17:50:23

标签: javascript jquery

更新

我现在已经解决了这个问题,改变了这一行:

   idList.push(this.id);

为:

 $(this).attr('id') 

我正在尝试遍历我页面上的所有复选框,并将所有已检查的ID添加到数组中。我让它循环遍历每个复选框,并检测它是否被选中,但是我无法将每个选中复选框的ID添加到数组中。

有人能告诉我哪里出错了吗?

感谢。

使用Javascript:

if (element == 'deleteButton' || element == 'allowButton')
            {
                //For testing.
                    //alert("Button Clicked");
                //Create an empty array, so it can be re-sized at run time.
                var idList = [];
                //Loop through all checkboxes, adding each ones id to an array. 
                $('#reported_rages').find('input[type="checkbox"]:checked').each(function () {
                   //this is the current checkbox   
                    //For testing.
                        //alert("Checked");

                    //Add the current ID to the array
                    idList.push(this.id);
                });

                //return false; // or do something else.
            }
            alert(idList);

1 个答案:

答案 0 :(得分:0)

这里尝试实现这些想法。

JSFiddle

/*sets variable to global so it can be accessed outside of function*/
var idList = [];
function run(){
    /*clears the original variable*/
    idList = [];
    $('#data').find('input[type="checkbox"]:checked').each(function () {
        idList.push(this.id);
    });
    /*prints after list is populated*/
    console.log(idList);
    $('#results').html(idList);
}
/*binds run function to click of submit*/
$('#submit').click(run);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id='data'>
    <input id='1' type='checkbox' />
    <input id='2' type='checkbox' />
    <input id='3' type='checkbox' />
    <input id='4' type='checkbox' />
    <input id='5' type='checkbox' />
</div>
<div id='results'></div>
<button id='submit'>Submit</button>