how to bind input and td together into a single click event?

how to bind input and td together into a single click event?

menkey18menkey18 Posts: 12Questions: 0Answers: 0
edited July 2011 in General
Hi, I have got a checkbox in each cell, and I only want to show the cell as selected when the checkbox is clicked.

Here is the code I've written:

[code]

$('#example td input').live('click', function() {
$('#example td').live( 'click', function() {
if ($(this).hasClass('cell_selected') )
$(this).removeClass('cell_selected');
else
$(this).addClass('cell_selected');
} );
} );

[/code]

The problem is it takes 2 click events show the cell as selected, so it is unsuccessful.

Would like to know how to improve it.

Cheers.

Replies

  • fbasfbas Posts: 1,094Questions: 4Answers: 0
    jquery lets you trigger events with .trigger(). so for the input's parent (or whatever it's relationship is to the input) trigger it's click event

    [code]
    $('#example td input').live('click', function() {
    $(this).parent().trigger("click");
    } );

    $('#example td').live( 'click', function() {
    if ($(this).hasClass('cell_selected') )
    $(this).removeClass('cell_selected');
    else
    $(this).addClass('cell_selected');
    } );
    [/code]
  • dmolavidmolavi Posts: 65Questions: 0Answers: 0
    actually, i think the first portion should be:
    [code]$('#example td,input').live('click', function() {
    $(this).parent().trigger("click");
    } ); [/code]

    note the addition of the comma between 'td' and 'input'.
  • menkey18menkey18 Posts: 12Questions: 0Answers: 0
    Thank you very much, I have made it work. Here is my code:

    [code]

    $('#example td input').live('click', function() {
    if ($(this).parent().hasClass('cell_selected') )
    $(this).parent().removeClass('cell_selected');
    else
    $(this).parent().addClass('cell_selected');
    } );

    [/code]

    Cheers!!
  • fbasfbas Posts: 1,094Questions: 4Answers: 0
    jquery loves you. http://api.jquery.com/toggleClass/

    [code]
    $('#example td input').live('click', function() {
    $(this).parent().toggleClass('cell_selected');
    } );
    [/code]
This discussion has been closed.