开发者

Getting the "newest" selected option's text from multiple select list

开发者 https://www.devze.com 2023-01-08 22:28 出处:网络
I have a HTML select list, which can have multiple selects: <select id=\"mySelect\" name=\"myList\" multiple=\"multiple\" size=\"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 w开发者_高级运维ill 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?


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());


Set a onClick on the option instead of the select:

$('#mySelect option').click(function() {
    if ($(this).attr('selected')) {
        alert($(this).val());
    }
});


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消