How do you limit options selected in a html select

2020-01-25 00:59发布

I'm using a select tag in a form I'm making that allows multiple selections, but I want to make the maximum amount of selections upto 10. Is this possible using javascript or jquery?

Thanks in advance!

8条回答
放我归山
2楼-- · 2020-01-25 01:32

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!

查看更多
叼着烟拽天下
3楼-- · 2020-01-25 01:35

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

查看更多
beautiful°
4楼-- · 2020-01-25 01:40

Here is some full code for you to use...gotta love the Google AJAX API Playground :-)

Edit 1: Note: this only lets you choose 5 because I didn't feel like copy/pasting another 10 options :-)

<!--
  copyright (c) 2009 Google inc.

  You are free to copy and use this sample.
  License can be found here: http://code.google.com/apis/ajaxsearch/faq/#license
-->

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="content-type" content="text/html; charset=utf-8"/>
    <title>Sample Select Maximum with jQuery</title>
    <script src="http://www.google.com/jsapi?key=ABQIAAAA1XbMiDxx_BTCY2_FkPh06RRaGTYH6UMl8mADNa0YKuWNNa8VNxQEerTAUcfkyrr6OwBovxn7TDAH5Q">    </script>
    <script type="text/javascript">
    google.load("jquery", "1");

    $(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>
  </head>
  <body style="font-family: Arial;border: 0 none;">
    <select multiple id='testbox'>
      <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>
  </body>
</html>

Demo

查看更多
你好瞎i
5楼-- · 2020-01-25 01:45

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

查看更多
兄弟一词,经得起流年.
6楼-- · 2020-01-25 01:46

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);
  });   
查看更多
Explosion°爆炸
7楼-- · 2020-01-25 01:50

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

查看更多
登录 后发表回答