【问题标题】:How do you limit options selected in a html select box?您如何限制在 html 选择框中选择的选项?
【发布时间】:2011-01-04 00:14:13
【问题描述】:

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

提前致谢!

【问题讨论】:

  • 欢迎来到 StackOverflow,Tposed!
  • 好的,我会更深入地了解它。这是一个内部公司电子邮件表单,带有一个自动生成的选择框,其中包含每个员工的姓名。我正在更新它,因此它会显示您已经选择了哪些名称(这是一个 looooooong 列表),因此有一些客户端验证您没有选择超过 10 个名称(显然有服务器端代码来防止这种情况) .选择标签的 id 是“recipient_userid”。我会发布我到目前为止所拥有的
  • $(document).ready(function(){ var last_valid_selection = null; $("#recipient_userid").change(function(event){ var selected = ""; $("#recipient_userid option:selected").each(function () { selected += "
  • " + $(this).text() + "
  • "; }); $("#currentlySelected").html(选择); }).change(); });
  • 标签: javascript jquery html forms


    【解决方案1】:

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

    编辑 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

    ​

    【讨论】:

    • 这几乎是完美的!如果 last_valid_selection 是一个数组,它不会再次选择它。不过谢谢!
    • 我不确定你的意思。如果last_valid_selection 是一个数组,什么不会再次选择它?
    • 您可能希望将last_valid_selection 移出全局范围并进入ready 匿名函数。
    • @Justin Johnson - 好点。我仍然对什么不起作用感到困惑。在 Chrome 中完美运行(目前无法测试 IE)。
    • @Topher,除非你准备好读心,否则不要回答! :)
    【解决方案2】:

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

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

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

    【讨论】:

    • 如果我们使用键盘或滑动点击,这将不起作用。
    【解决方案3】:

    这个答案在这些情况下有效:

    • 正常点击
    • 仅 mousedown(鼠标在 mouseup 之前移到外面)
    • 键盘
    • 如果有相同值的不同选项

    代码:

    $('#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

    或者,对于不支持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

    【讨论】:

      【解决方案4】:

      使用 jQuery,您可以将函数附加到更改事件,因为它是多选,所以 val() 将是一个数组。您始终可以检查数组的长度并在其预定义大小时执行某些操作。以下代码演示了如何知道选择了多少项。

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

      【讨论】:

      • 这会有很大帮助。有没有办法在选择框中取消选择所有内容?
      • @tposed - 使用 jQuery,您可以简单地调用 $('#myselectbox_id').val(null);
      • 您可以使用:$("#select").val([]); 在选择列表中不设置任何选项。
      【解决方案5】:

      想通了!这是生成的代码:

      $(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();
      });
      

      感谢大家的帮助!

      【讨论】:

      • Tombed,这不是论坛。您的贡献应该只存在于原始问题中(您可以随意编辑它)。您应该接受此处提供的众多优秀答案之一。
      • Tombed,乔纳森是绝对正确的。这个想法是提出一个问题并选择最佳答案(您甚至会因此而获得一些声誉)。我很少不选择答案,更罕见的是我回答自己的问题。然而,这个社区在这里是为了互相帮助,我很高兴我们帮助了你。
      • 对不起,我不知道。
      【解决方案6】:

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

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

      罗伯

      【讨论】:

        【解决方案7】:

        你可以使用 jQuery

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

        【讨论】:

          【解决方案8】:

          瞧! 不需要 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;              
                  }
              }
          

          吉鲁三

          【讨论】:

          • 这个例子似乎不完整,也许是故意的,从那时起它会涉及jQuery?什么是 selectCountryCode?​​span>
          • 没有必要避免使用 jQuery;无论如何都需要运行 Selectize。
          猜你喜欢
          相关资源
          最近更新 更多
          热门标签