I want to capture what option has been selected from dropdown. Here the problem is when option is being clicked TR click event is called because select
doesn't have click event.
How can I stop TR click event when drop down is clicked?
<html>
<script>
function check1() {
alert("TR clicked");
}
function check2() {
alert("drop_down clicked");
}
</script>
<table border=1>
<tr onclick="check1();">
<td>My Options</td>
<td>
<select name="" id="drop_down" onchange="check2();">
<option value="A">A</option>
<option value="B">B</option>
</select>
</td>
</tr>
</table>
Use
addEventListener()
instead of inline attribute eventHandlers. At the end of theeventListener()
, or at the end of callback, adde.stopPropagation()
so the event never bubbles thereby never reaching<tr>
.<tr>
will need to be referenced as it is relative to another table component such as<table>
or<td>
. Although inline attribute events stick to anything (including a<tr>
tag), it will become detrimental to maintaining such a layout (as I suspect it is already occurring). This is why it has been strongly suggested thataddEventListener()
be used instead of inline events.In the following demo:
If
<select>
is clicked the console logs its value.If a
<td>
is clicked then it logs a generic 'click'It will not log both at click event
All modern browsers are supported
Details commented in demo
Demo
You can just check what element triggered the click, and if it was the drop down, ignore the event:
jsfiddle sample
If you want the JS to be more generic and not check for specific ID of elements, you can also change its logic to look for elements having a custom attribute defined:
To make it work with your code, change the HTML to this: (the value of the attribute doesn't matter)
updated fiddle
one more thing you can do is get event target,
to support in all browsers just capture event and pass it as param
You need to capture
click
event on<select>
and prevent its propagation:or you can try to simply return
false
forclick
event for<select>
:I found this solution to work best for me:
The good thing about this solution is that it works for all child elements inside the desired target element. For e.g, this logic works when a select element is clicked and it also works when any of the options inside the select element are clicked.
Downside: the path array needs to be looped through.