Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

with an input checkbox inside a table row, can i add click event to row and still be able to click input

I have a table:

<table>
  <tr>
    <td>Something</td>
    <td>Something Else</td>
    <td><input type='checkbox' value='clickme' id='yes'></td>
  </tr>

For the user, if they click the row, they get more data about the row, and if they click the checkbox, they are presented with some other options. how can i listen for each event in jquery. My problem is that the click for checkbox obviously fires off the event for the row click

$('tr').click(function(){
     alert('you clicked the row');
});
$('#yes').change(function(){
      alert('you clicked the checkbox');
});

if element is created dynamically, would this work:

        $('#someTableId').on('click','#yes',function(e){
            alert($(this).attr('id'));
            e.stopPropagation();
    });

Update: the answer to part 2 yes.

like image 565
bart2puck Avatar asked Jun 17 '15 05:06

bart2puck


2 Answers

You can use event.stopPropagation() try this:-

$('#yes').click(function(e){
 e.stopPropagation();
});

Demo

like image 72
Mohit Kumar Avatar answered Oct 05 '22 23:10

Mohit Kumar


Use event.stopPropagation to stop event bubbling up, you will need to bind new click event for checkbox.

Prevents the event from bubbling up the DOM tree, preventing any parent handlers from being notified of the event.

Live Demo

$('#yes').click(function(event){         
      event.stopPropagation();
});

One other alternative could be withing adding addition click handler for checkbox is to skip the processing of tr click handler when event source is checkbox.

Live Demo

$('tr').click(function(event){
    if(event.target.id === 'yes') return;
     alert('you clicked the row');        
});
like image 38
Adil Avatar answered Oct 06 '22 00:10

Adil