Javascript 如何限制在 html 选择框中选择的选项?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2046205/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-22 22:33:00  来源:igfitidea点击:

How do you limit options selected in a html select box?

javascriptjqueryhtmlforms

提问by tominated

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?

我正在使用允许多选的表单中的 select 标签,但我希望最多选择 10 个。这可以使用 javascript 或 jquery 吗?

Thanks in advance!

提前致谢!

回答by Topher Fangio

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

这里有一些完整的代码供您使用...一定要喜欢 Google AJAX API Playground :-)

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

编辑 1:注意:这只能让您选择 5 个,因为我不想复制/粘贴另外 10 个选项:-)

<!--
  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

演示

?

?

回答by Sampson

This would limit the user to 3 options:

这会将用户限制为 3 个选项:

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

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

小提琴:http: //jsfiddle.net/2GrYk/

回答by Oriol

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
  • 正常点击
  • 只有mousedown(鼠标在mouseup之前移到外面)
  • 键盘
  • 如果有相同值的不同选项

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,

或者,对于不支持的旧浏览器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

演示

回答by Vincent Ramdhanie

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.

使用 jQuery,您可以将一个函数附加到更改事件,因为它是一个多选,所以 val() 将是一个数组。你总是可以检查数组的长度,如果它是预定义的大小,就可以做一些事情。以下代码演示了如何知道选择了多少项。

  $("#select").change(function(){
        alert($(this).val().length);
  });   

回答by tominated

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!

感谢您的帮助!

回答by hepcat72

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

我基本上合并了几个提供的答案,以制作特定于特定 ID 的内容:

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

Rob

回答by Ashwin

You can use jQuery

你可以使用 jQuery

  $("select").change(function () {
      if($("select option:selected").length > 3) {
          //your code here
      }
  });

回答by jilu

Voila! No Jquery necessary.

瞧!不需要Jquery。

    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

吉鲁散