0

I have the checkboxes and its values are populated from the database. I can select and deselect all the checkbox but I am not able to get the values of individual checked checkbox. This is what I have done so far, for the checkbox populating from database:

<form>

<br>
<input type="checkbox" id="All"> <b>Select/DeSelect All</b><br>

<?php
$sql = 'SELECT Subject_Category from {extdb_subjects} where level=1 ';
$res = db_query($sql);

foreach ($res as $row)
{
 echo "<input type='checkbox' id='sub_names' name='{$row->Subject_Category}'
    value='{$row->Subject_Category}'";

  echo ">{$row->Subject_Category}";
  echo "<br>";
}
?>

</form>

JQuery script for selecting de selecting all the check box and individual display of the checked checkbox:

jQuery(function(){

 jQuery('#All').change(function() {


    var checkboxes = jQuery(this).closest('form').find(':checkbox');

    if(jQuery(this).is(':checked')) {
        checkboxes.attr('checked', 'checked');


    } else {
        checkboxes.removeAttr('checked');

    }


    });

  jQuery('#sub_names').change(function() { //This is not able to get the values

    if(jQuery(this).is(':checked')) {
      alert(jQuery("input[type=checkbox]:checked").val());


    } 


    });

});

Any suggestions will be highly appreciated.

Mohan Timilsina
  • 490
  • 6
  • 25
  • This might help http://stackoverflow.com/questions/786142/how-to-retrieve-checkboxes-values-in-jquery – noob Mar 02 '13 at 09:17
  • 2
    Your problem is you have many element with same ID (I think) so only the first one will have your onChange handler. –  Mar 02 '13 at 09:18
  • @RC yes, because of that only first element value show up when clicking the checkbox and for the rest it has no effect. – Mohan Timilsina Mar 02 '13 at 09:26
  • Use a class and not an ID –  Mar 02 '13 at 09:27
  • Yes, use classes not ids. But you still have a problem in that `.val()` will return only the value of the first selected element. If you want to alert the values of all selected elements then you will need to build a string by looping through the jQuery selection. – Beetroot-Beetroot Mar 02 '13 at 09:32
  • The examples in jQuery's documentation for [.map()](http://api.jquery.com/map/) detail a potential solution. – Beetroot-Beetroot Mar 02 '13 at 09:37

1 Answers1

0

This seems odd to me. You check to see if this is checked, then you try to grab some arbitrary checked box value. Try this.

jQuery('#sub_names').change(function() { //This is not able to get the values
  if(jQuery(this).is(':checked')) {
    alert(jQuery("input[type=checkbox]:checked").val());
  } 
}

try:

   jQuery('input[type=checkbox]').click(function(){
      if(jQuery(this).is(':checked')){
         console.log( $(this).val() )
       }
   })
james emanon
  • 11,185
  • 11
  • 56
  • 97