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

后端 未结 8 768
一生所求
一生所求 2020-11-27 19:07

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

相关标签:
8条回答
  • 2020-11-27 19:47

    You can use jQuery

      $("select").change(function () {
          if($("select option:selected").length > 3) {
              //your code here
          }
      });
    
    0 讨论(0)
  • 2020-11-27 19:51

    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

    0 讨论(0)
提交回复
热议问题