How can I limit selected options in select element when using shift key

1.1k Views Asked by At

HTML

<select id="my-select" multiple="multiple" size="8" style="width:200px">
    <option value="0">0</option>
    <option value="1">1</option>
    <option value="2">2</option>
    <option value="3">3</option>
    <option value="4">4</option>
    <option value="5">5</option>
    <option value="6">6</option>
    <option value="7">7</option>
    <option value="8">8</option>
    <option value="9">9</option>
    <option value="10">10</option>
    <option value="11">11</option>
    <option value="12">12</option>
    <option value="13">13</option>
    <option value="14">14</option>
    <option value="15">15</option>
</select>

JQUERY

$('#my-select option').on('click',function(){
    var count = $('#my-select').find('option:selected').length;
    $('#dg').html(count);
        if(count>10){
            $(this).attr('selected',false); 
    alert('limit 10');
         }
 });

http://jsfiddle.net/LxNMm/

When you click on the options, calculate count of selected options and limit it to 10, but if you click on the options with pressing shift key and select a range, selection could be greater than 10. How can a detect count of selected options when select a range with pressing shift key

2

There are 2 best solutions below

1
On

Don't use the click event of the <option />s but the change event of the <select />

$('#my-select').on('change', function () {
    var count = $(this).find('option:selected').length;
    $('#dg').html(count);
    if (count > 10) {
        $(this).find("option").prop('selected', false);
        alert('error');
    }
})

fiddle

0
On

You can try updating the values this way:

 $('#my-select').on('change', function () {
    var count = $(this).find('option:selected').length;
    $('#dg').html(count);
    if (count > 10) {
       $('option:gt(9)', this).attr('selected', false);
       count = $(this).find('option:selected').length;
       $('#dg').html(count);
       alert('error');
    }
});

Your updated demo fiddle