3

I'm trying to do something when a user selects an option from a select box - As simple as can be right? I'm using JQuery 1.3.1 to register a click handler with the id of the select box. Everything was fine until I tested using Chrome and Safari and found it didn't work.

  1. Firefox 3.05 - YES
  2. I.E 7.0.5730.13 - YES
  3. IE6Eolas - YES
  4. Sarafi 3.2.1 - NO
  5. Chrome 1.0.154.43 - NO

See below code:

<html>
<head>
    <script language="javascript" type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.1/jquery.min.js"></script>
    <script language="javascript">
    $(document).ready(function(){
        $('#myoption').click(function() { alert('Select Dropdown was clicked: '+ $('#myoption').val()); });
    });     
    </script>
</head>
<body>
    <select id="myoption">
    <option value="A">A</option>
    <option value="B">B</option>
    </select>
</body>
</html>

Anyone know what I should be doing for this to work? The alert does eventually get triggered but only after double-clicking the select box?

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
Tom
  • 14,041
  • 16
  • 64
  • 80

2 Answers2

5

I found my problem. For Select boxes, you need to register a handler for a "change" event rather than a "click" event. It's strange that Firefox and IE work with the click event.

To sum up, the following code works across all browsers:

<html>
<head>
    <script language="javascript" type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.1/jquery.min.js"></script>
    <script language="javascript">
    $(document).ready(function(){
        $('#myoption').change(function() { alert('Select Dropdown was clicked: '+ $('#myoption').val()); });
    });         
    </script>
</head>
<body>
    <select id="myoption">
    <option value="A">A</option>
    <option value="B">B</option>
    </select>
</body>
</html>
Tom
  • 14,041
  • 16
  • 64
  • 80
  • I think "change" does not work in IE. IIRC, it is not triggered before the element looses focus. – Tomalak Jan 23 '09 at 08:42
  • Yes, change on select works in IE - the live version of the code I used can be seen in the select box at http://www.peopleperhour.com/reg_sup.php (when "other" is selected, a textbox is displayed asking for further info). – Tom Jan 23 '09 at 21:19
1

Safari and Chrome are both webkit based browsers. Webkit uses the native dropdown elements from your OS instead of implementing dropdowns itself, and unfortunately native dropdowns do not support a click events. For the same reason they also do not support CSS for option elements or other neat tricks.

The only cross-browser way to get those working is to implement this by hand using an <ul> and a lot of javascript.

Wichert Akkerman
  • 4,918
  • 2
  • 23
  • 30