views:

92

answers:

6

Say I have this dropdown:

<select name="color" multiple="multiple">
<option value="red">Red</option>
<option value="green">Green</option>
<option value="blue">Blue</option>
</select>

So basically more than 1 color can be selected. What I'd like is that if a user selects red, and then clicks green, i'd like a function to be called each time which pops up a message box saying the color which was most recently clicked.

I've tried this:

<option value="red" onclick="alert('red');">Red</option>
<option value="green" onclick="alert('green');">Green</option>
<option value="blue" onclick="alert('blue');">Blue</option>

This works in firefox and chrome, but not in IE.

Any ideas?

+2  A: 
$("select[name='color']").change(function() {
    // multipleValues will be an array
    var multipleValues = $(this).val() || [];

    // Alert the list of values
    alert(multipleValues[multipleValues.length - 1]);
});

Here's another examples: http://api.jquery.com/val/

TiuTalk
The problem is, multiple options can be selected. If i select green, it works, then if hold CTRL and click on red, it still says green although i want it to then say red
Click Upvote
@Click Upvote - Now it support multiple values :)
TiuTalk
But I don't want it to say both green and red, I want it to only say the option which was just clicked. E.g, I have green selected, I hold CTRL and click red, I want it to then only say red. If I have both green and red selected and I click blue, I want it to only say blue, and so on
Click Upvote
There are ways that options can be selected many-at-a-time (shift-click). What do you want to happen then? The user can use up- and down-arrow to navigate the list and spacebar to make selections, so you might also want to trap keyboard events. What about when a color is de-selected?
Pointy
@Click Upvote - You'll need `alert(multipleValues[multipleValues.length - 1]);`.. Corrected :)
TiuTalk
@Point - If you use the 'change' event it will fire everytime that a option is selected and de-selected. :)
TiuTalk
@TiuTalk - no it won't, keyboard selection won't work, just as it won't work for `click` events on a select. I just tried it out.
karim79
This is not correct. The last element in `multipleValues` is always the latest selected element in the option list. E.g. if I have three options `1`, `2` and `3`, `1` and `3` are selected and I select (in addition) `2`, then then alerted value is `3`.
Felix Kling
A: 

This will alert only the last (most recent) selected value. Calling $(this).val() using the select's change handler will return an array of all your selected values:

$(document).ready(function() {
     $("select[name=color] option").click(function() {
        alert($(this).val());
    });
});
karim79
Beware that you can select a option using keyboard and it will not trigger the click event :)
TiuTalk
Doesn't work in IE
Click Upvote
@Click Upvote - probably because I was using the select's `name` as a class selector. I've edited it, try it now if you like.
karim79
A: 

I am not sure what you exactly want. This will always alert the last selected color:

$(function(){
    var selected = Array();
    $('select[name=color] option').click(function() {
        if($(this).is(':selected')) {
           selected.push($(this).val());
        }
        else {
           for(var i = 0; i < selected.length;i++) {
               if(selected[i] == $(this).val()) {
                   selected = selected.splice(i,1);
               }
           }
        }  
        alert(selected[selected.length -1])
    });         
});

The array is used to maintain the history of selected colors.

For the last clicked color, it is simpler:

$(function(){
    $('select[name=color] option').click(function() {
        alert($(this).val());
    });         
});
Felix Kling
As I said to karmin79: Beware that you can select a option using keyboard and it will not trigger the click event :)
TiuTalk
+1  A: 

Since you using jQuery,I suggest you to take a look at this superb plugins. This plugins will transform a multiple select dropdown into a checkbox list, so user can select multiple values with easy.

To get the values, I suggest you use fieldValue methods from jQuery form plugins. It's a robust way to get value from any type of form element. Beside, you can use this plugins to submit your form via AJAX easily.

Donny Kurnia
+1  A: 

The following code should do what I think you're after. Each time an item is selected, it compares the current list of selections against the previous list, and works out which items have changed:

<html>
  <head>
    <script type="text/javascript">
      function getselected(selectobject) {
        var results = {};
        for (var i=0; i<selectobject.options.length; i++) {
          var option = selectobject.options[i];
          var value = option.value;
          results[value] = option.selected;
        }
        return results;
      }

      var currentselect = {};

      function change () {
        var selectobject = document.getElementById("colorchooser");
        var newselect = getselected(selectobject);
        for (var k in newselect) {
          if (currentselect[k] != newselect[k]) {
            if (newselect[k]) {
              alert("Option " + k + " selected");
            } else {
              alert("Option " + k + " deselected");
            }
          }
        } 
        currentselect = newselect;
      } 
    </script>
  </head>
  <body>
    <select id="colorchooser"
            name="color"
            multiple="multiple"
            onchange='javascript:change();'
            >
      <option value="red">Red</option>
      <option value="green">Green</option>
      <option value="blue">Blue</option>
    </select>
  </body>
</html>

It should work just as well in Internet Explorer as Firefox et al.

Tim
A: 

This is so complicated to accomplish that I used a simpler option of listing the items with a checkbox next to them and a select/unselect all button. That works much better and is also supported by IE. Thanks to everyone for their answers.

Click Upvote
Do have a look at my answer ( http://stackoverflow.com/questions/2261518/how-to-get-the-value-of-a-multiple-option-dropdown/2262938#2262938 ) before you abandon your preferred approach. It's not that complicated once you break down the requirement into smaller pieces.
Tim