How to limit multiple select options
Author
Author

Robert Nicjoo [68]

I love Laravel & WordPress, interested to pass little knowledge that I have to others.

Qr-Code

Scan to visit on mobile

TJD STUDIO is Hiring

Photographer & Videographer

Apply now Jabodetabek

How to limit multiple select options

Sometimes you are in need to limit users of choosing options in your multiple select-boxes, in this short tutorial I'm providing you a solution that prevent users of selecting more than 3 options.

Note: it's optional to you how many option users can select " don't worry :) "

 

Logic

  1. Finding our select-box with providing id (can be class also)
  2. collecting selected options and count them
  3. if is more than 3 show alert in browser and let user know he/she is only able to choose 3 options
  4. if they don't care! remove extra selected options value and not sending them to back-end

 

Code

 

<select name="tags[]" id="tags" class="form-control" multiple>
  <option value="1">One</option>
  <option value="2">Two</option>
  <option value="3">Three</option>
  <option value="4">Four</option>
  <option value="5">Five</option>
  <option value="6">Six</option>
</select>

 

<script type="text/javascript">
    $(document).ready(function() {
        var arr = new Array();
        $("#tags").change(function() {
            $(this).find("option:selected")
            if ($(this).find("option:selected").length > 3) {
                $(this).find("option").removeAttr("selected");
                $(this).val(arr);
                alert('You can only choose 3!');
            }
            else {
                arr = new Array();
                $(this).find("option:selected").each(function(index, item) {
                    arr.push($(item).val());
                });
            }
        });
    });
</script>

 

Dig in code

 

$(document).ready(function() {

running our code when page is fully loaded

 

$("#tags").change(function() {

getting select-box by providing id. in this case id="tags"

 

$(this).find("option:selected")

finding and counting selected options

 

if ($(this).find("option:selected").length > 3) {
  $(this).find("option").removeAttr("selected");
  $(this).val(arr);
  alert('You can only choose 3!');
}

if selected options are more than 3 show alert and remove extra values and send first 3 values to back-end only.

 

else {
  arr = new Array();
  $(this).find("option:selected").each(function(index, item) {
    arr.push($(item).val());
  });
}

if user only selected 3 options send those values to back-end.

 

 

That's all :).

 

Don't forget to vote this article by helping of emojis below this post.

How do you like this article?

Back to top