UPDATE
I have now solved it, changing this line:
idList.push(this.id);
to:
$(this).attr('id')
I am trying to loop through all of the checkboxes on my page and add the ID's of all that are checked to an array. I have it looping through each checkbox, and detecting whether or not it is checked, but I am having trouble adding the ID of each checked checkbox to an array.
Could someone tell me where I am going wrong?
Thanks.
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);
Here try implementing these ideas.
/*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>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.