arth81
arth81

Reputation: 229

Prevent multiselect from checking last value from

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

Answers (3)

brroshan
brroshan

Reputation: 1650

Try this, it will prevent you from selecting all options:

$("#custom-header").change(function () {
    if ($(this).val().length > 4) {
        $(this).val("");
    }
});

Updated fiddle

Or if you like short ternary:

$("#custom-header").change(function () {   
    $(this).val($(this).val().length > 4 ? "" : $(this).val());
});

Upvotes: 2

Sebri Zouhaier
Sebri Zouhaier

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

Marcos P&#233;rez Gude
Marcos P&#233;rez Gude

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

Related Questions