0

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:

$(".checkboxadd").click(function(){
                    $('[id*="add_policies_checkbox"]').each(function(){
                      //alert(this.value);
                      var data=this.value;
                      $("#div_to_add_this_checkbox_value").append("Info added"+data);
                    });
});//end ajaxifypolicies

3 Answers3

0

Use $.fn.prop :

$(':checkbox').prop('checked');
// return true or false
Abdennour TOUMI
  • 87,526
  • 38
  • 249
  • 254
  • $('[id*="add_policies_checkbox"]:checkbox').prop('checked'); Is this how I should do this? –  Jul 25 '16 at 18:40
  • Each add_policies_checkbox has a number, add_policies_checkbox1, add_policies_checkbox2, etc.... Thinking about it I could make class for this if that is possible, I just need every checkbox to be it's own unique ID. –  Jul 25 '16 at 18:43
  • will return for only one checkbox....not sure what this is supposed to accomplish – charlietfl Jul 25 '16 at 18:43
0

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

$(".checkboxadd").click(function(){
                    $('[id^="add_policies_checkbox"]').each(function(i, v){
                      //alert(this.value);
                      if($(v).prop('checked')){
                      var data=$(v).val();
                      $("#div_to_add_this_checkbox_value").append("Info added"+data);}
                    });
});//end ajaxifypolicies
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></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>
Shubham Khatri
  • 270,417
  • 55
  • 406
  • 400
0

You are very close, see the changes below:

$(".checkboxadd").click(function(){
                $('#add_policies_checkbox:checked').each(function(){
                  //alert(this.value);
                  var data = $(this).value
                  $("#div_to_add_this_checkbox_value").append("Info added"+data);
                });
});//end ajaxifypolicies