Getting the “newest” selected text option from multiple selection lists

I have an HTML select list that can have multiple selections:

<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 the option text every time I select it. I am using jQuery for this:

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

It looks quite simple, however, if there are already some selected options in the favorites list, it will also return the text. As an example, if I had already chosen the Second option, after selecting the Fourth, the warning would bring me this - SecondFourth. So, is there a short, easy way with jQuery to get only the “current” selected option text, or do I need to play with strings and filter the new text?

+3
source share
3

- , , , :

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;
}); ​

, .val() <select multiple>, <option>. , , , ($.inArray(val, arr) == -1 ), . - , .text().

value="" , , .filter(),

$(this).children().filter(function() {
  return this.value == newVal[i];
}).text());
+3

onClick :

$('#mySelect option').click(function() {
    if ($(this).attr('selected')) {
        alert($(this).val());
    }
});
+1
var val = ''
$('#mySelect').change(function() {
   newVal = $('#mySelect option:selected').text();
   val += newVal;
   alert(val); # you need this.
   val = newVal;
});

or allow playback yet

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

Greetings.

0
source

Source: https://habr.com/ru/post/1755967/


All Articles