How do you limit the number of options selected in an HTML <select> element?
Asked Answered
L

9

26

I'm using a <select> element in a form I'm making that allows multiple selections, but I want to limit the maximum amount of selections to 10. Is this possible using JavaScript or jQuery?

Labyrinth answered 12/1, 2010 at 2:0 Comment(4)
Welcome to StackOverflow, Tominated!Breastpin
OK, i'll put it more into contect. it's an internal company email form with an automaticvally generated select box with every employee's name. I'm updating it so it will show which names you've already selected (it's a looooooong list) and so there is some client validation that you haven't selected more than 10 names (there is obviously sever side code to prevent this). The id for the select tag is "recipient_userid". i'll post what i have so farLabyrinth
$(document).ready(function(){ var last_valid_selection = null; $("#recipient_userid").change(function(event){ var selected = ""; $("#recipient_userid option:selected").each(function () { selected += "<li>" + $(this).text() + "</li>"; }); $("#currentlySelected").html(selected); }).change(); });Labyrinth
Possible duplicate of Multiple Select limit number of selectionKoran
O
30

Here is some full code for you to use:

$(document).ready(function() {

  var last_valid_selection = null;

  $('#testbox').change(function(event) {
    if ($(this).val().length > 5) {
      alert('You can only choose 5!');
      $(this).val(last_valid_selection);
    } else {
      last_valid_selection = $(this).val();
    }
  });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script>
<select multiple id="testbox" size="10">
  <option value='1'>First Option</option>
  <option value='2'>Second Option</option>
  <option value='3'>Third Option</option>
  <option value='4'>Fourth Option</option>
  <option value='5'>Fifth Option</option>
  <option value='6'>Sixth Option</option>
  <option value='7'>Seventh Option</option>
  <option value='8'>Eighth Option</option>
  <option value='9'>Ninth Option</option>
  <option value='10'>Tenth Option</option>
</select>
Odessa answered 12/1, 2010 at 2:23 Comment(10)
that's almost perfect! it doesn't select it again if last_valid_selection is an array. Thanks, though!Labyrinth
I'm not sure what you mean. What doesn't select it again if last_valid_selection is an array?Odessa
You may want to move last_valid_selection out of the global scope and into the ready anonymous function.Alaster
@Justin Johnson - Good point. I'm still confused as to what doesn't work though. Works perfectly in Chrome (can't test IE at the moment).Odessa
Works fine in FF 3.5.6 as well. I don't know what the down vote is forAlaster
it's not working with the code i have so far. i have a comment on the op with soem more info on what i'm doingLabyrinth
@Labyrinth - You downvoted me because the example I gave you doesn't work for your exact situation?Odessa
@Topher, don't answer unless you're prepared to read minds! :)Breastpin
@Jonathan +1 - LMAO. Thanks, I'm about to head to bed and I needed a laugh :-)Odessa
+1 Good idea using jQuery's .val() to get all values (unlike .value in JS). Here is a demo. The problem is that it doesn't work in the rare case with repeated values.Airline
B
16

This would limit the user to 3 options:

$("select").on("click", "option", function () {
    if ( 3 <= $(this).siblings(":selected").length ) {
        $(this).removeAttr("selected");
    }
});​​​​​​​​​​

Fiddle: http://jsfiddle.net/2GrYk/

Breastpin answered 12/1, 2010 at 2:27 Comment(1)
This won't work if we use keyboard, or a glide'n click.Bellyband
A
5

This answer works in those cases:

  • Normal click
  • Only mousedown (mouse is moved outside before mouseup)
  • Keyboard
  • If there are different options with the same value

Code:

$('#mySelect').on('change', function() {
    if (this.selectedOptions.length < 4) {
        $(this).find(':selected').addClass('selected');
        $(this).find(':not(:selected)').removeClass('selected');
    }else
        $(this)
        .find(':selected:not(.selected)')
        .prop('selected', false);
});

Demo

Or, for old browsers that don't support selectedOptions,

$('#mySelect').on('change', function() {
    var $sel = $(this).find(':selected');
    if ($sel.length < 4) {
        $sel.addClass('selected');
        $(this).find(':not(:selected)').removeClass('selected');
    }else
        $(this)
        .find(':selected:not(.selected)')
        .prop('selected', false);
});

Demo

Airline answered 27/5, 2014 at 23:53 Comment(0)
P
3

Using jQuery you can attach a function to the change event and since it is a multiple select the val() will be an array. You can always check the length of the array and do something if its a predefined size. The following code demonstrates how you will know how many items are selected.

  $("#select").change(function(){
        alert($(this).val().length);
  });   
Printery answered 12/1, 2010 at 2:15 Comment(3)
that will help a lot. is there a way to deselect evrything in a select box, also?Labyrinth
@Labyrinth - Using jQuery, you can simply call $('#myselectbox_id').val(null);Odessa
You can use this: $("#select").val([]); to set no options in the select list.Printery
L
2

figured it out! here's the resulting code:

$(document).ready(function(){

var last_valid_selection = null;
var selected = "";

$("#recipient_userid").change(function(event){

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

        alert('You can only choose 10!');
        $(this).val(last_valid_selection);

    } else {

        last_valid_selection = $("#recipient_userid").val();

        $("#recipient_userid option:selected").each(function () {
            selected += "<li>" + $(this).text() + "</li>";
        });

        $("#currentlySelected").html(selected);
        selected = "";
    }

}).change();
});

Thanks for all your help guys!

Labyrinth answered 12/1, 2010 at 3:23 Comment(3)
Tominated, this is not a forum. Your contributes ought only exist in the original question (you can edit it as much as you like). You should accept one of the many fine answers that were provided here.Breastpin
Tominated, Jonathan is absolutely correct. The idea is to ask a question and select the best answer (you even get a few reputation for doing so). Very rarely do I not select an answer and even more rare is it that I answer my own question. However, this community is here to help each other, and I'm glad we helped you.Odessa
Sorry guys, I was unaware about that.Labyrinth
A
1

I basically merged a couple of the provided answers to make something specific to a particular ID:

$("#mySelect").on("click", "option", function(){
    var max = 3;
    if ( max <= $(this).siblings(":selected").length ) {
        alert("Only " + max + " selections allowed.");
        $(this).removeAttr("selected");
    }
});

Rob

Acetone answered 25/5, 2013 at 19:23 Comment(0)
T
0

You can use jQuery

  $("select").change(function () {
      if($("select option:selected").length > 3) {
          //your code here
      }
  });
Tread answered 4/1, 2013 at 12:55 Comment(0)
S
0

Here a pure vanilla JavaScript example, based on jilu's example.

const selectEls = document.querySelectorAll('select[multiple]');

selectEls.forEach((selectEl) => {
    selectEl.addEventListener('change', (e) => {

        const currentEl = e.currentTarget;

        let is = 0;
        for (let i = 0; i < currentEl.length; i++) {
            if (currentEl.options[i].selected) {
                is++;
            }
            if (is > 3) { // if you want more than 3 selected options, change the number here
                currentEl.options[i].selected = false;
            }
        }

    })
});
Smalltime answered 26/1, 2023 at 15:17 Comment(0)
H
-1

Voila! No Jquery necessary.

    var is = 0;
    for (var i = 0; i < selectCountryCode.length; i++) {
        if (selectCountryCode.options[i].selected) {
            is++;
        }
        if (is > 3) {
            selectCountryCode.options[i].selected = false;              
        }
    }

Jilusan

Hendren answered 18/3, 2016 at 16:5 Comment(2)
This example seems incomplete, perhaps by intent since then it would involve jQuery? What is selectCountryCode?Sussi
There's no need to avoid jQuery; it is anyway needed to run Selectize.Construction

© 2022 - 2024 — McMap. All rights reserved.