0

The problem about following code is when I click select tag, it triggers <tr> onclick event, how to resolve that?

<table>
  <tr onclick="window.location = 'http://example.com'">
    <td>...</td>
    <td>...</td>
    <td>...</td>
    <td>
      <select>
             <option>...</option>
             <option>...</option>
          </select>
    </td>
  </tr>
</table>
Soolie
  • 1,812
  • 9
  • 21
jjoselon
  • 2,641
  • 4
  • 23
  • 37
  • This seems to be already asked and answered: https://stackoverflow.com/questions/13966734/child-element-click-event-trigger-the-parent-click-event – ibis Dec 19 '17 at 15:16
  • @Soolie, that edit was totally meaningless, and your edit comment doesn't really apply to the edit. You made no change to the code and hardly fixed any of the grammatical errors in the text – Nick is tired Dec 20 '17 at 03:09
  • @NickA Umm... Sorry mate... What I meant to do is to make the question more semantically readable. When a question is asked, people don't throw a pile of code on your face and then explain. My views. :) – Soolie Dec 20 '17 at 09:18

2 Answers2

3

This is event bubbling. You have to make sure that the event is not bubbled up. Just add this event in the <select>'s onclick event.

<select onclick="event.stopPropagation(); event.stopImmediatePropagation();">

<div onclick="console.log('Clicked DIV.');">
  <select onclick="event.stopPropagation(); event.stopImmediatePropagation();">
    <option></option>
    <option>1</option>
    <option>2</option>
  </select>
</div>

<table>
  <tr onclick="console.log('Clicked TR.');">
    <td>
      <select onclick="event.stopPropagation(); event.stopImmediatePropagation();">
        <option></option>
        <option>1</option>
        <option>2</option>
      </select>
    </td>
  </tr>
</table>
Soolie
  • 1,812
  • 9
  • 21
  • 3
    This is the right approach, but you shouldn't need to call both `stopPropagation()` and `stopImmediatePropagation()`. Either would work in this case to prevent bubbling. The only time `stopImmediatePropagation()` is necessary is when there are more than one event listener attached to an element, which doesn't seem to be the case here. [Check this out](https://codeplanet.io/preventdefault-vs-stoppropagation-vs-stopimmediatepropagation/) for more info. – AdamJ Dec 19 '17 at 15:10
  • @AdamJ Thank you so much for the link. `:)` – Soolie Dec 19 '17 at 15:12
0

You can use event.stopPropagation() on the select element to prevents further propagation of the current event in the capturing and bubbling phases.

<tr onclick="window.location = 'http://example.com'">
<td>...</td>
<td>...</td>
<td>...</td>
<td>
  <select onclick="event.stopPropagation(); ">
     <option>...</option>
     <option>...</option>
  </select>
</td>    
</tr>
Ahmader
  • 1
  • 1