samrockon
samrockon

Reputation: 923

jquery - disabling click function on parent element

i have structure like this

<table><tr><td></td><td><input type="button" name="button"></td></tr></table>
<script> 
$('tr').click(function(){window.alert('tr');})
$(':input').click(function(){window.alert('input');})
</script>

when i click on the button, tr click event also called. is there any way to disable click event on parent element? the only solution i found is to add class to parent element and inside its click function check for it. for example:

 <script> 
$('tr').click(function(){ if(!$(this).hasClass('disable')) { window.alert('tr');  }  $(this).removeClass('disable');  })
$(':input').click(function(){window.alert('input'); $(this).closest('tr').addClass('disable');})
</script>

Upvotes: 9

Views: 10476

Answers (4)

benjaroa
benjaroa

Reputation: 377

You also can check the propagation status using event.stopimmediatepropagation() and event.isImmediatePropagationStopped()

$(':input').click(function(e){
    e.stopImmediatePropagation();
    var status = e.isImmediatePropagationStopped();

    //CHECK
    console.log(status); //true-false
});

Upvotes: 0

Mechlar
Mechlar

Reputation: 4984

.stopPropagation() would work but if you don't want to stop the entire event then you can just fire it if the targets match.

See this thread.

Upvotes: 3

Bob Fincheimer
Bob Fincheimer

Reputation: 18076

Stop Propagation?

http://api.jquery.com/event.stopPropagation/

This will prevent the click event from bubbling through its parents.

Upvotes: 2

Reigel Gallarde
Reigel Gallarde

Reputation: 65284

use .stopPropagation()

$('tr').click(function(){
   window.alert('tr');
});
$(':input').click(function(e){
   e.stopPropagation();
   window.alert('input');
});

demo

Upvotes: 15

Related Questions