How to Multiple Select limit number of selection using jQuery

I was doing to set a max-limit of selection on drop down list as one user select if(max limit is 2) of the options other will not select automatically. You may also like How to Send HTML Form array in Codeigniter using Ajax and How to Submit Multiple Form array in Codeigniter using Ajax.

HTML Code

<select class="form-control MultiSelectSubCouseLimit" multiple="" required="" name="multiple_block[]">
    <option value="61">1 Task 1: Line Graphs - Present Perfect - Prepositions of Time</option>
    <option value="62">2 Task 2: Problems &amp; Solutions</option>
    <option value="63">3 Task 1:  Pie &amp; Bar Charts (Comparatives Superlatives)</option>
    <option value="64">4 Task 2: Advantages &amp; Disadvantages</option>
    <option value="65">5 Task 1:  Tables</option>
    <option value="66">6 Task 2: Discuss both these views…</option>
    <option value="67">7 Task 1:  2-Map comparison / 1 -Map description/ comparatives/conditionals</option>
    <option value="68">8 Task 2: Opinion Essay</option>
    <option value="69">9 Task 1:  2-Charts</option>
    <option value="70">10 Mini Mock Exam</option>
</select>

Jquery Code

var last_valid_selection = null;
$('.MultiSelectSubCouseLimit').change(function(event) {
    if ($(this).val().length > 2) {
        $(this).val(last_valid_selection);
    } 
    else 
    {
      last_valid_selection = $(this).val();
    }
});

Leave a Reply

Your email address will not be published. Required fields are marked *