Get the last item selected in a multi Select box [jQuery]

by: Moshe Brevda

Lets say you have a select box and you want to limit the amount options that can be selected. And lets say you want to do that with jQuery. Here is how:

The first thing to keep in mind is that you cant use onClick() here (aka $.click()), as selecting more than one items doesn’t fire a click event. Instead, we will use $.change().

var maxSelected = 2; 
$('select[name=selectTest]').change(function(e){ 
    if ($(this).val().length > maxSelected) { 
        alert('You cannot have more than ' + maxSelected + ' items selected')
    } 
})

This will alert the user if they try to select more than maxSelected of items - in this case two. However, there selection will still be valid! What we need is to get the last item they selected - and to de-select it. Luckily, that item is passed in the event property (e) as e.currentTarget.value, so we can just use that property to unset the last selected item:

var maxSelected = 2; 
$('select[name=selectTest]').change(function(e){ 
    if ($(this).val().length > maxSelected) { 
        alert('You cannot have more than ' + maxSelected + ' items selected'); 
        $('select[name=selectTest] option[value=' + e.currentTarget.value + ']').attr('selected', false) 
    } 
})

Happy coding!