5

I want to add an event trigger on a drop-down <select> list. Example (jsFiddle):

$( document ).ready(function() { $('.lorem').click(function() { alert('ipsum'); }); });
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <select> <option class="lorem">1</option> <option class="lorem">2</option> </select>

With Firefox, when I click on it, it triggers fine. But on webkit (Chrome/Safari etc), it does not work. Why?

8
  • 1
    Do you specifically need to add an event listener on the <option> elements, or do you just want to listen for input on the <select> element? Commented Mar 7, 2019 at 14:16
  • 1
    Do you specifically want to know why? It's probably a quirk of how click events bubble in each browser. The solution is to use change of the select not click of the options. Commented Mar 7, 2019 at 14:18
  • 2
    Well the solution is covered in the duplicate I've flagged Commented Mar 7, 2019 at 14:19
  • 2
    Aside from click not working on option elements in all browsers (the reason is simply down to their interpretation of the spec. It's not documented anywhere) it's also bad practice for accessibility reasons. Always use change, then the problem is moot. Commented Mar 7, 2019 at 14:20
  • 2
    Vote to reopen. This question is not a duplicate. The OP is specifically asking why the code works with Firefox but not with WebKit, and the linked duplicate does not address that issue. Commented Mar 8, 2019 at 18:34

2 Answers 2

1

If you are using this to detect input changes, you can use .change():

$( document ).ready(function() { $("select").change(function(e) { console.log($("select").val()); }); });
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <select> <option class="lorem">1</option> <option class="lorem">2</option> </select>

Sign up to request clarification or add additional context in comments.

Comments

1

You could instead use a change event on your select element and then check where the selected option has the lorem class like so:

$(document).ready(function() { $('select').on('change', function() { if ($("option:selected", this).hasClass('lorem')) { alert('ipsum'); } }); });
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <select> <option class="lorem">1</option> <option class="lorem">2</option> <option class="foo">3</option> </select>

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.