How to limit the number of selected items in multi-choice. For example:

<select multiple="multiple" name="region"> <option value="1">Киев</option> <option value="2">Москва</option> <option value="3">Лондон</option> <option value="4">Париж</option> <option value="5">Рим</option> <option value="6">Мадрид</option> </select> 

It is necessary that you can choose a maximum of 3 cities. After popped warning that all items are selected.

    4 answers 4

    Sort of

     <select multiple="multiple" name="region"> <option value="1" onclick="myFunc(this)">Киев</option> <option value="2" onclick="myFunc(this)">Москва</option> <option value="3" onclick="myFunc(this)">Лондон</option> <option value="4" onclick="myFunc(this)">Париж</option> <option value="5" onclick="myFunc(this)">Рим</option> <option value="6" onclick="myFunc(this)">Мадрид</option> </select> 

    Further JS:

     function myFunc(elem){ var region = document.getElementById('region'); var countSelected = 0; //Считаем for (var i = 0; i < region.options.length; i++){ if (region.options[i].selected) countSelected++; } if (countSelected > 3){//Отменяем последнее выделение elem.selected = false; alert('Больше выбирать нельзя'); } } 
    • Thanks helped ... - Oll

    Select select add id :

     <select multiple="multiple" name="region" id="region"> 

    And check for javascript:

     var count = 0; var region = document.getElementById('region'); for (var i=0; i<region.options.length; i++){ if (region.options[i].selected) count++; } alert('Выбрано городов: ' + count); 
    • And how to cancel the last selected item? - Anton Mukhin
    • And where is the limit ???? I looked at the fact that 10 and went on ... to look at the fact that more than 10 ... - Oll
    • one
      This is a way to count cities. You have to politely inform the user. - Tolyandre 1:59 pm

    It is possible so:

     $(function(){ var select = $('#new-select'); select.click(function(){ var a = select.find('option:selected'); if(a.length==3){ select.attr('disabled','disabled') } }); }); 
       <select multiple="multiple" maxlength="3"> <option value="1">Киев</option> <option value="2">Москва</option> <option value="3">Лондон</option> <option value="4">Париж</option> <option value="5">Рим</option> <option value="6">Мадрид</option> </select> <script> var s = document.getElementsByTagName('select'), i = 0; while(s[i]){ // вешаем обработчик на options, лежащие внутри select с заданным maxlength if(!this.parentNode.getAttribute('maxlength')) var o = s[i].options, j = 0; while(o[j]){ o[j].onclick = function(){ if(this.selected) if(!restrictSelect(this.parentNode)) this.selected = false; }; ++j; } ++i; } function restrictSelect(x){ var max = x.getAttribute('maxlength'); var o = x.options, n = 0, i = 0; while(o[i]){ if(o[i].selected) if(++n > max) return false; ++i; } return true; } </script>