简体   繁体   中英

Create array of checked checkboxes with jquery

I'm trying to get an array of chechked checkboxes. So far I used the following code:

var data ={
td1_1_checkbox:  $("#table #tr1 #td1_1 #td1_1_checkbox").val(),
td1_2_checkbox:  $("#table #tr1 #td1_2 #td1_2_checkbox").val(),
td1_3_checkbox:  $("#table #tr1 #td1_3 #td1_3_checkbox").val(),
td1_4_checkbox:  $("#table #tr1 #td1_4 #td1_4_checkbox").val()
}

This code but only got me the value "on". I tried with .checked() but didn't get a result.

You have to use .is(':checked') to get the checked/unchecked state of checkbox. Also, since you have a unique id for each of the checkbox so you can simply use the id selector as $("#td1_1_checkbox") , $("#td1_2_checkbox") and so on.

 var data ={ td1_1_checkbox: $("#td1_1_checkbox").is(':checked'), td1_2_checkbox: $("#td1_2_checkbox").is(':checked'), td1_3_checkbox: $("#td1_3_checkbox").is(':checked'), td1_4_checkbox: $("#td1_4_checkbox").is(':checked') } console.log(data);
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <input id='td1_1_checkbox' type='checkbox' checked='checked' />1 <input id='td1_2_checkbox' type='checkbox' checked='checked' />2 <input id='td1_3_checkbox' type='checkbox' checked='checked' />3 <input id='td1_4_checkbox' type='checkbox' checked='checked' />4

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM