views:

52

answers:

3

I have a HTML select list, which can have multiple selects:

<select id="mySelect" name="myList" multiple="multiple" size="3">
   <option value="1">First</option>
   <option value="2">Second</option>
   <option value="3">Third</option> `
   <option value="4">Fourth</option> 
   ...
</select>

I want to get an option's text everytime i choose it. I use jQuery to do this:

$('#mySelect').change(function() {
   alert($('#mySelect option:selected').text());
}); 

Looks simple enough, however if select list has already some selected options - it will return their text too. As example, if i had already selected the "Second" option, after choosing "Fourth" one, alert would bring me this - "SecondFourth". So is there any short, simple way with jQuery to get only the "current" selected option's text or do i have to play with strings and filter new text?

+1  A: 

You could do something like this, keeping the old value array and checking which new one isn't in there, like this:

var val;
$('#mySelect').change(function() {
 var newVal = $(this).val();
 for(var i=0; i<newVal.length; i++) {
     if($.inArray(newVal[i], val) == -1)
       alert($(this).find('option[value="' + newVal[i] + '"]').text());
 }
 val = newVal;
}); ​

Give it a try here, When you call .val() on a <select multiple> it returns an array of the values of its selected <option> elements. We're simply storing that, and when the selection changes, looping through the new values, if the new value was in the old value array ($.inArray(val, arr) == -1 if not found) then that's the new value. After that we're just using an attribute-equals selector to grab the element and get its .text().

If the value="" may contains quotes or other special characters that would interfere with the selector, use .filter() instead, like this:

$(this).children().filter(function() {
  return this.value == newVal[i];
}).text());
Nick Craver
A: 
var val = ''
$('#mySelect').change(function() {
   newVal = $('#mySelect option:selected').text();
   val += newVal;
   alert(val); # you need this.
   val = newVal;
});

or let's play some more

val = ''; 
$('#id_timezone')
  .focus(
    function(){
        val = $('#id_timezone option:selected').text();
    })
  .change(
    function(){
        alert(val+$('#id_timezone option:selected').text())
    });

Cheers.

simplyharsh
This would append all the options selected every time (not just the one you clicked on), resulting in a very large/growing string :)
Nick Craver
A: 

Set a onClick on the option instead of the select:

$('#mySelect option').click(function() {
    if ($(this).attr('selected')) {
        alert($(this).val());
    }
});
Sjoerd
this will not work in any version of IE, though ...
Gaby
Indeed. Thanks.
Sjoerd