Reputation: 229
I'd like to implement the multiple select element that would prevent users from checking all of the values from the list (all -1 is acceptable). I've written some jquery code, but I don't know what is wrong with it. Any help? HTML:
<select class='custom-header' id='custom-header' multiple='multiple' name="my-select">
<option class="test" value='elem_1'>elem 1</option>
<option class="test" value='elem_2'>elem 2</option>
<option class="test" value='elem_3'>elem 3</option>
<option class="test" value='elem_4'>elem 4</option>
<option value='elem_100'>elem 100</option>
</select>
JS:
var userChoice = $(".test");
$.each(userChoice, function(index,value){
if(index = userChoice.length -1){
alert("The last was clicked.");
}
});
Upvotes: 1
Views: 65
Reputation: 1650
Try this, it will prevent you from selecting all options:
$("#custom-header").change(function () {
if ($(this).val().length > 4) {
$(this).val("");
}
});
Or if you like short ternary:
$("#custom-header").change(function () {
$(this).val($(this).val().length > 4 ? "" : $(this).val());
});
Upvotes: 2
Reputation: 745
Using This code You will get an alert when all option are selected
$('#custom-header').change(function(){
if($("#custom-header > option").length==$("#custom-header :selected").length){
alert("The last was clicked.");
}
});
Upvotes: 2
Reputation: 22158
you can use last-child selector:
var userChoice = $(".test:last-child");
userChoice.on('click', function() {
// stuff;
});
It is better if you use onchange event
$('#custom-header').on('change', function() {
if($(this).selectedIndex == $('#custom-header .test').length)
});
Upvotes: 0