Sol Sol - 1 year ago 80
Javascript Question

How to get the Value of a checkbox from JQuery?

I have some checkboxes and want to add their value into JQuery. I have been able to retrieve the value but it gets every checkbox value with the .each jquery command. I wasn't sure how to get only the value of that specific checkbox that is checked so I can use the append command to display the data.

The checkbox:

<input id="add_policies_checkbox<?php echo $row[toolID]; ?>" type="checkbox" value=<?php echo $row[toolID]; ?> />

The button that submits the form for JQuery to handle:

<input type="button" name="action" class="btn btn-success checkboxadd" value="Add Policy" />

JQuery - Not sure how to get only the information (value) from the add_policies_checkbox that is checked:

var data=this.value;
$("#div_to_add_this_checkbox_value").append("Info added"+data);
});//end ajaxifypolicies

Answer Source

use [id^="add_policies_checkbox"] as selector to loop over all checkboxes with id starting with add_policies_checkbox and check their checked property

                    $('[id^="add_policies_checkbox"]').each(function(i, v){
                      var data=$(v).val();
                      $("#div_to_add_this_checkbox_value").append("Info added"+data);}
});//end ajaxifypolicies
<script src=""></script>
<input type="checkbox" value="something1" id="add_policies_checkbox1"/>
<input type="checkbox" value="something2" id="add_policies_checkbox2"/>
<input type="checkbox" value="something3" id="add_policies_checkbox3"/>
<button class="checkboxadd">Submit</button>
<div id="div_to_add_this_checkbox_value"></div>

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download