Max Williams
Max Williams

Reputation: 32933

Click checkbox by clicking in the surrounding td

I have a table that in one column has a checkbox. I want the user to be able to check (or uncheck) the checkbox by clicking on the checkbox OR the surrounding td. To complicate (possibly) things a little further, the checkbox has an onchange event set on it (i've put doSomething() in here just for clarity).

Here's my current html: as you can see i'm using jQuery.

<tr>
  <td onclick="jQuery(this).children('input').click();">
    <input id="dvdorders-77_packed" name="dvd_orders[77][packed]" onchange="doSomething()" type="checkbox" value="1">
  </td>
</tr>

I thought this was working ok but then noticed that when i click on the actual checkbox, this counts as a click on the checkbox AND a click on the td, effectively clicking twice on the checkbox and so setting it and unsetting it again instantly (and triggering doSomething() twice).

There must be a nicer way to do this - anyone? thanks, max

Upvotes: 1

Views: 707

Answers (3)

Julien Lafont
Julien Lafont

Reputation: 7877

You can check the target of the event to restrict your action. It's the best generic solution I know.

Simply check if :

event.target === this

Example :

$("#mytable td").has("input:checkbox").click(function(event) {
    if (event.target === this) {
        var $checkbox = $(this).children("input:checkbox");
        $checkbox.attr('checked', !$checkbox.attr('checked')); 

        // Or simply $(this).children("input:checkbox").trigger('click');
    }
});

Demo : http://jsfiddle.net/Yb6YF/6/

Upvotes: 1

AgnosticDev
AgnosticDev

Reputation: 1853

      <tr>
        <td id="clickTd">
         <input id="dvdorders-77_packed" name="dvd_orders[77][packed]"
         onchange="doSomething()" type="checkbox" value="1">
       </td>
     </tr>

     jQuery('#clickTd').click(function(e)
     {
        e.preventDefault();
        var id = jQuery(this).attr('id');

        if(id == "dvdorders-77_packed")
        {
            //perform logic
        }
        else
        {
            //perform other logic
        }
      });

This is what I was thinking, dont know if this is on the order of what you were doing?

Upvotes: 0

James Montagne
James Montagne

Reputation: 78650

You want to stop propogation:

$("#dvdorders-77_packed").click(function(e){
  // do your stuff
  e.stopPropogation();
});

This could also be done inline if needed (though not ideal). I separated it out for clarity.

Upvotes: 1

Related Questions