I have a <select multiple="multiple" id="multi">
in my website, and I have a script in jquery that has this function:
$("#multi").on("change",function(){})
I want to access the latest selected item of the select
in this function(the last one selected by user), how can I do that?
I have a <select multiple="multiple" id="multi">
in my website, and I have a script in jquery that has this function:
$("#multi").on("change",function(){})
I want to access the latest selected item of the select
in this function(the last one selected by user), how can I do that?
- The last, as in the last one selected by the user, or the last selected option in the HTML etc. – adeneo Commented Aug 20, 2014 at 6:12
- I mean the last one selected by user – Navid777 Commented Aug 20, 2014 at 6:23
- Then you should probably answer the ments when they are posted, and test the answers before you accept them – adeneo Commented Aug 20, 2014 at 6:25
6 Answers
Reset to default 6To get the last selected by the user, you can do this
var map = $("#multi").on("change",function(){
var p = $("#multi option:selected").map(function() {
return this.value;
}).get(),
set1 = map.filter(function(i) {
return p.indexOf(i) < 0;
}),
set2 = p.filter(function(i) {
return map.indexOf(i) < 0;
}),
last = (set1.length ? set1 : set2)[0];
map = p;
// "last" contains the last one selected /unselected
}).find('option:selected').map(function() {return this.value}).get();
FIDDLE
You can use :selected
selector and :last
(or alternatively .last()
) this way:
$('#multi').change(function() {
console.log( $(this).find('option:selected:last').text() );
});
JSFiddle
I think you are searching for this
$("#multi").on("change",function(){
alert($("option:selected:last",this).val());
})
DEMO
var last_value;
$('#multi').change(function() {
last_value = this.val();
alert(last_value);
});
define global variable, and every time ur dropdown change the seletion, u can replace the last selected value with the new one.
FIDDLE :
Less coding with Optimize solution : Why not use the is
function of jquery:
$(document).ready(function(){
$('#multi option').click(function(){
if($(this).is(':selected'))
console.log('you have select' + $(this).val());
else
console.log('you have Unselect' + $(this).val());
});
});
How about this
var = last;
$('#multi').find('option').each(function() {
$(this).click(function() {
if($(this).hasAttr('selected')) {
last = $(this);
}
}
}