0

I am new in jquery.

I am using multiple select plugin jquery.

I want that the user can't select more than 3 options.

Here I have also disabled the selectall option.

Here is my code:

<select multiple id='testbox'>
  <option value='1'>First Option</option>
  <option value='2'>Second Option</option>
  <option value='3'>Third Option</option>
  <option value='4'>Fourth Option</option>
  <option value='5'>Fifth Option</option>
</select>

Jquery code:

$("select").multipleSelect({
    selectAll: false
 });

Please help me. Thanks in advance :)

Elydasian
  • 2,016
  • 5
  • 23
  • 41
kanu mahajan
  • 77
  • 2
  • 11

3 Answers3

1

EDIT :

There working jsFiddle example with multi-select plugin

var limit = 3;

var $multiSel = $("select").multipleSelect({
placeholder: "Here is the placeholder",
width: 200,
filter: true,
selectAll: false,
onClick: function(view) {
    var $checkboxes = $multiSel.next().find("input[type='checkbox']").not(":checked");
    var selectedLen = $multiSel.multipleSelect('getSelects').length;
    if (selectedLen >= limit) {
       $checkboxes.prop("disabled", true);
    } else {
       $checkboxes.prop("disabled", false);
    }
 }
});
EA-Lille
  • 561
  • 7
  • 21
  • This will not work if you select multiple items together using select. click on first element and then press shift and click on last element. – Rajesh Jun 12 '17 at 11:24
  • Edited with multiple-select plugin, is that better ? – EA-Lille Jun 12 '17 at 11:32
  • thanks @EA-Lille that's what i am looking for!! thanks buddy – kanu mahajan Jun 12 '17 at 11:43
  • is it possible @EA-Lille if user clicks on 4 th checkbox it shows me alert message you can't select more . i waiting for your reply – kanu mahajan Jun 12 '17 at 11:53
  • You can't detect a click on disabled element. See this post https://stackoverflow.com/a/924731/6703798 .The only solution you have is to use CSS to simulate disabled and then you will be able a click on the fake disabled input. Like this https://stackoverflow.com/a/16109366/6703798 – EA-Lille Jun 12 '17 at 12:54
0

add change event for select and check for length of selected options

  $("select").change(function () {
      if($("select option:selected").length > 3) {
          // you can disable rest of the things here
      }
  });
Dinesh undefined
  • 5,490
  • 2
  • 19
  • 40
0

You could do

if($("select").multipleSelect("getSelects").length > 3)
{
   alert('Not allowed');
}
Rahul
  • 2,374
  • 2
  • 9
  • 17