I have a number of select boxes that have been set to accept multiple values. Is there anyway that I can use jQuery to get the last selected value? I've tried using the following:
var latest_value = $("option:selected",this).val();
and it returned nothing. I only want the last selected value and not the array of values.
Thank you in advance
As requested here's the HTML I've cut the list down as it's too long:
<select id="style-list" name="style-list[]" class="attrs" multiple="multiple">
<option value="7">2 Pack</option>
<option value="10">3 Pack</option>
<option value="12">4 Pack</option>
</select>
Then at the top of the page I have the following (I have 8 of these, but I've shown a few so that you can see that I'm using multiple instances of the multiselect widget:
$(document).ready(function(){
$("#product-list").multiselect({
selectedList: 4,
noneSelectedText: "Product",
minWidth: 190
}).multiselectfilter();
$("#style-list").multiselect({
selectedList: 4,
noneSelectedText: "Style",
minWidth: 190
}).multiselectfilter();
$("#feature-list").multiselect({
selectedList: 4,
noneSelectedText: "Features",
minWidth: 190
}).multiselectfilter();
});
and then I have this in a seperate js file:
$(function(){
$(".attrs").on("multiselectclick", function(event, ui){
var latest_value = $('option', this).filter(':selected:last').val();
alert (latest_value);
var view = $("#currentview").val();
var page = 1;
run_ajax(view,page);
});
})
Thank you
Use the last function: like this
$("#style-list option:selected").last().val()
yes as @KannanK said, above answers not giving correct value, because it's storing values based on drop down display order, so if select from bottom to top, then will give wrong value.
I got one better logic to achieve this. on every change of drop down will store into one global variable, so that we can get last selected value in differOpt variable.
var lastSelectedValues = [];
$('#yourID').change(function(e) {
debugger;
var currentSelVals = $('#yourID').val();
var differOpt =arr_diff(currentSelVals,lastSelectedValues);
lastSelectedValues = currentSelVals;
});
function arr_diff (a1, a2) {
var a = [], diff = [];
for (var i = 0; i < a1.length; i++) {
a[a1[i]] = true;
}
for (var i = 0; i < a2.length; i++) {
if (a[a2[i]]) {
delete a[a2[i]];
} else {
a[a2[i]] = true;
}
}
for (var k in a) {
diff.push(k);
}
return diff;
}
Updating one more better solution we can go with onChange option its giving correct value either select/unselect
$(function () { $('#datadownAutpState').multiselect(
onChange: function(option, checked) {
alert(option.val + ' option ' + (checked ? 'selected' : 'deselected'));
}
});});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With