Multiple Select limit number of selection

I want user to select maximum of only three options from multiple select options. I tried this code so far:

<select id="userRequest_activity" required name="activity[]" class="multiselect form-control" multiple="multiple">
    <option value="2">Bungee Jumping</option>
    <option value="3">Camping</option>
    <option value="5">Mountain Biking</option>
    <option value="6">Rappelling</option>
    <option value="7">Rock Climbing / Bouldering</option>
    <option value="8">Skiing</option>
    <option value="10">Wild Life (Safari)</option>
    <option value="11">Canoeing &amp; Kayaking</option>
    <option value="12">Rafting</option>
    <option value="13">Sailing</option>
    <option value="14">Scuba Diving</option>
    <option value="15">Snorkeling</option>
    <option value="16">Surfing</option>
    <option value="18">Hang Gliding</option>
    <option value="19">Hot-air Ballooning</option>
    <option value="20">Micro-light Aircrafts</option>
    <option value="21">Paragliding</option>
    <option value="22">Paramotoring</option>
    <option value="23">Parasailing</option>
    <option value="24">Skydiving / Parachuting</option>
    <option value="25">Zip-line / Flying Fox</option>
    <option value="26">Caving</option>
    <option value="27">Cycling</option>
    <option value="28">Fishing &amp; Angling</option>
    <option value="29">Motorbike trips</option>
    <option value="30">Nature Walks</option>
    <option value="31">Road Trips</option>
    <option value="32">Zorbing</option>
    <option value="33">Trekking Hiking and Mountaineering</option>
    <option value="34">Backpacking</option>
    <option value="61">Water</option>
</select>

The javascript code:

<script type="text/javascript">
$("select").change(function() {
    if ($("select option:selected").length > 3) {
        $(this).removeAttr("selected");
        alert('You can select upto 3 options only');
    }
});
</script>

This code shows the alert box when selected more than 3 options but still allow access to select the 4th, 5th, 6th and so on selections with the alert box appearing. How to validate this?

Answers:

Answer

Try this...

Check length and deselect after reach maximum select

<select id="userRequest_activity" required name="activity[]" class="multiselect form-control" multiple="multiple">
    <option value="2">Bungee Jumping</option>
    <option value="3">Camping</option>
    <option value="5">Mountain Biking</option>
    <option value="6">Rappelling</option>
    <option value="7">Rock Climbing / Bouldering</option>
    <option value="8">Skiing</option>
    <option value="10">Wild Life (Safari)</option>
    <option value="11">Canoeing &amp; Kayaking</option>
    <option value="12">Rafting</option>
    <option value="13">Sailing</option>
    <option value="14">Scuba Diving</option>
    <option value="15">Snorkeling</option>
    <option value="16">Surfing</option>
    <option value="18">Hang Gliding</option>
    <option value="19">Hot-air Ballooning</option>
    <option value="20">Micro-light Aircrafts</option>
    <option value="21">Paragliding</option>
    <option value="22">Paramotoring</option>
    <option value="23">Parasailing</option>
    <option value="24">Skydiving / Parachuting</option>
    <option value="25">Zip-line / Flying Fox</option>
    <option value="26">Caving</option>
    <option value="27">Cycling</option>
    <option value="28">Fishing &amp; Angling</option>
    <option value="29">Motorbike trips</option>
    <option value="30">Nature Walks</option>
    <option value="31">Road Trips</option>
    <option value="32">Zorbing</option>
    <option value="33">Trekking Hiking and Mountaineering</option>
    <option value="34">Backpacking</option>
    <option value="61">Water</option>
</select>

    <script type="text/javascript">


        $(document).ready(function() {

          var last_valid_selection = null;

          $('#userRequest_activity').change(function(event) {

            if ($(this).val().length > 3) {

              $(this).val(last_valid_selection);
            } else {
              last_valid_selection = $(this).val();
            }
          });
        });
        </script>

DEMO:http://jsfiddle.net/9c3sevuv/

Answer

You are using this inside change event, which is reference to select.

Try this:

$("select").on('click', 'option', function() {
    if ($("select option:selected").length > 3) {
        $(this).removeAttr("selected");
        // alert('You can select upto 3 options only');
    }
});

Demo: http://jsfiddle.net/tusharj/tmkzebnj/

EDIT

$("select").on('change', function(e) {
    if (Object.keys($(this).val()).length > 3) {
        $('option[value="' + $(this).val().toString().split(',')[3] + '"]').prop('selected', false);
    }
});

Demo: http://jsfiddle.net/tusharj/tmkzebnj/1/

Answer

You can disable the unselected options once the user selected the maximum limit and enable them again when the total selection count goes below the maximum limit.

Here is the sample code,

    function maxAllowedMultiselect(obj, maxAllowedCount) {
            var selectedOptions = jQuery('#'+obj.id+" option[value!=\'\']:selected");
            if (selectedOptions.length >= maxAllowedCount) {
                if (selectedOptions.length > maxAllowedCount) {
                    selectedOptions.each(function(i) {
                        if (i >= maxAllowedCount) {
                            jQuery(this).prop("selected",false);
                        }
                    });
                }
                jQuery('#'+obj.id+' option[value!=\'\']').not(':selected').prop("disabled",true);
            } else {
                jQuery('#'+obj.id+' option[value!=\'\']').prop("disabled",false);
            }
        }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="userRequest_activity" name="activity[]" onchange="maxAllowedMultiselect(this, 2)" multiple>
  <option value="1">Bungee Jumping</option>
  <option value="2">Camping</option>
  <option value="3">Mountain Biking</option>
  <option value="4">Rappelling</option>
  <option value="5">Rock Climbing / Bouldering</option>
  <option value="6">Skiing</option>
  <option value="7">Wild Life (Safari)</option>
  <option value="8">Canoeing &amp; Kayaking</option>
  <option value="9">Rafting</option>
  <option value="10">Sailing</option>
</select>

Answer

Try this Fiddle.

$("select option").click(function() {
    if ($("select option:selected").length > 3) {
        $(this).removeAttr("selected");
        alert('You can select upto 3 options only');
    }
});
Answer

Try this

$("select").change(function() {
    if($("select option:selected").length > 3) { 
     alert('You can select upto 3 options only');
     $(this).removeAttr("selected");
  }

});

DEMO

Tags

Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.