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?

skomisa
  • 16,436
  • 7
  • 61
  • 102
Henrik Petterson
  • 6,862
  • 20
  • 71
  • 155
  • 1
    Do you specifically need to add an event listener on the ` – user7290573 Mar 07 '19 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. – Liam Mar 07 '19 at 14:18
  • 1
    Yes, as stated in my question, with a solution as well. – Henrik Petterson Mar 07 '19 at 14:18
  • 2
    Well the solution is covered in the duplicate I've flagged – Liam Mar 07 '19 at 14:19
  • 1
    @Liam Great, but those answers do not provide an answer *why* this is working on FF and not webkit. – Henrik Petterson Mar 07 '19 at 14:20
  • 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. – Rory McCrossan Mar 07 '19 at 14:20
  • @RoryMcCrossan Thanks! – Henrik Petterson Mar 07 '19 at 14:28
  • 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. – skomisa Mar 08 '19 at 18:34

2 Answers2

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>
kzhao14
  • 2,470
  • 14
  • 21
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>
Nick Parsons
  • 45,728
  • 6
  • 46
  • 64