1

How to prevent on click event when dropdown's onChange? Please find below code and its output.

<html>
<head>
</head>

<body>
    <table>
        <tr onclick="onClick()">
            <td>
                <select onchange="onChange()">
                    <option value='1'>One</option>
                    <option value='2'>Two</option>
                    <option value='3'>Three</option>
                </select>
            </td>
        </tr>
    </table>

    <script type="text/javascript">
        function onClick() {
            console.log('on click event');
        }

        function onChange() {
            console.log('on change event')
            event.stopPropagation();
            event.cancelBubble = true;
        }
    </script>
</body>
</html>

Please find below console output on drop down selection

OUTPUT:

on click event
on change event
on click event
Himen Suthar
  • 80
  • 1
  • 3
  • 11

2 Answers2

3

There's a couple of ways to do this. You can put a check in your onClick() function to determine whether the click came from your select element:

function onClick(clickEvent) {
    const clickedElementType = clickEvent.target.nodeName;
    if (clickedElementType !== 'select') {
        console.log('on click event');
    }
}

//make sure we pass the event through from HTML
<tr onclick="onClick(event)">

Another way is to put an onclick handler on your <select> element and use event.stopPropagation() to prevent it from bubbling up to the <tr> element:

 function onSelectClick(clickEvent) {
     clickEvent.stopPropagation(); //this event won't hit the other click handler
 }

 //HTML
 <select onchange="onChange()" onclick="onSelectClick(event)">
Duncan Thacker
  • 5,073
  • 1
  • 10
  • 20
  • Your both solution is working.Thank you but Why event.stopPropagation(); in code provided not working inside onchange(). can you clarify? – Himen Suthar Feb 06 '19 at 09:50
  • 1
    The `change` event is a different type of event from the `click` event, so you need to handle them separately (even though they both get fired at roughly the same time). – Duncan Thacker Feb 06 '19 at 10:02
0

There are mainly two things to touch on events, event.stopPropagation() and event.preventDefault().

On SO there is a clear explanation on what is the difference between the two, please have a look over What's the difference between event.stopPropagation and event.preventDefault?

Anyway, as @duncan-thacker suggested before me, maybe you should think if that is the right place where to put your onClick event. You are forcing it to ignore the click on a child but you can avoid the issue if you try to use another html structure.

phaberest
  • 3,140
  • 3
  • 32
  • 40