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:51

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/

查看更多
家丑人穷心不美
3楼-- · 2020-01-25 01:52

You can use jQuery

  $("select").change(function () {
      if($("select option:selected").length > 3) {
          //your code here
      }
  });
查看更多
登录 后发表回答