views:

118

answers:

3

Hey, I am wondering how to get the id of a checkbox when it is checked.

This is what my HTML would probably look like at first:

<div class="check_filter">

    <div id="filter">
        <input type="checkbox" id="check1" /><label for="check1">Marketing</label>
        <input type="checkbox" id="check2" /><label for="check2">Automotive</label>
        <input type="checkbox" id="check3" /><label for="check3">Sports</label>
    </div>

</div><!-- End check_filter -->

I'm assuming the jQuery would look something like this:

$(document).ready(function() {    
    $(":checkbox").click(function(){
        var id = $(this).attr('id');

        $.post("index.php", { id: id });
       //return false to ensure the page doesn't refresh
       return false;
    });    
});

I'm trying to get the checked item id and then post that id in a mysql query to grab the results of the id from the database.

Thanks for any help on this.

A: 

The jQuery you provided works fine? You should probably remove the return false to show that the checkbox has been checked.

EDIT: $.post() is for an async request (AJAX technique) so there will be no page refresh.

EDIT 2: You may also want to see if the checkbox is checked (not just that it has been clicked):

$(document).ready(function() {    
  $(":checkbox").click(function(){
        var id = $(this).attr('id');
        var isChecked = $(this).attr('checked'));
        $.post("index.php", { id: id, isChecked: isChecked });
    });    
});
TheCloudlessSky
+1  A: 

You probably want the change event here, like this:

$(function() {
  $(":checkbox").change(function(){
    $.post("index.php", { id: this.id, checked: this.cheked });
  });    
});

This posts whenever a checkbox changes, and lets the PHP side know the ID and whether it's checked or not.

Nick Craver
+1 for `this.id`, etc, but you forgot to change the `click` to `change` (in the code). :o) EDIT: Has been corrected.
patrick dw
@patrick - Wops, fixed, @Generic - You can test it here: http://jsfiddle.net/nick_craver/zM4md/ It works with spacebar, etc :)
Nick Craver
@Nick - I made an example myself after I made the comment. Apologies, looks like it was fixed last year.
GenericTypeTea
A: 

You can better use jQuery get instead of post. It allows you to handle the output of your request: http://api.jquery.com/jQuery.get/

Example:

$(document).ready(function() {    
  $(':checkbox').click(function(){
        var id = $(this).attr('id');
        var isChecked = $(this).attr('checked'));
        $.get(
          'getcheckbox.php', 
          { id: id, isChecked: isChecked },
          function(data) {
            //return value in getcheckbox.php and use it in on complete function
            var result = data;
          }
        );
    });    
});
filster