Reputation: 145
I have a html Table like this:
<table>
<tr onClick="someFunc();">
<td>Foo</td>
<td><button onClick="anotherFunc();">Bar</button></td>
</tr>
</table>
and Javascript:
function somefunc(){
alert("Foo");
}
function anotherfunc(){
alert("Bar");
}
The problem is when I click on tr works fine but when I press on the button inside TD it fires both functions so I want when I click on the button to just fire the button function.
Upvotes: 0
Views: 72
Reputation: 93601
For starters, do not use inline handler with jQuery. That separates the handler from the registration for no good reason and leads to maintenance problems. Use classes or IDs to match the elements and use jQuery handlers.
The problem is event propagation. To stop the click propagating use e.stopPropagation()
in the handler:
<table>
<tr class="doSomeFunc">
<td>Foo</td>
<td><button class="doAnotherFunc">Bar</button></td>
</tr>
</table>
$('.doSomeFunc').click(function(e){
alert("Foo");
});
$('.doAnotherFunc').click(function(e){
e.stopPropagation();
alert("Bar");
});
If you want to stick with your existing non-jQuery code, just change this:
<button onClick="anotherFunc();return false;">
return false
from a mouse handler will do the same as e.stopPropagation()
and e.preventDefault()
.
Upvotes: 4
Reputation: 8291
You need to use e.stopPropagation();
Prevents the event from bubbling up the DOM tree, preventing any parent handlers from being notified of the event https://api.jquery.com/event.stoppropagation/
Here is a demo: https://jsfiddle.net/j81czwky/
$("tr").click(function(e){
alert("Foo");
})
$("button").click(function(e){
e.stopPropagation();
alert("Bar");
});
<table>
<tr>
<td>Foo</td>
<td><button>Bar</button></td>
</tr>
</table>
Upvotes: 0
Reputation: 2351
Your click
action is being propagated to all parent elements of the button
. To stop that, use event.cancelBubble = true
(or, if you're using jQuery you can use event.stopPropagation()
) in the click
event.
Upvotes: 2