如何限制 HTML
我正在制作的表单中使用
I'm using a <select>
element in a form I'm making that allows multiple selections, but I want to limit the maximum amount of selections to 10. Is this possible using JavaScript or jQuery?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(9)
这是一些完整的代码供您使用:
Here is some full code for you to use:
这会将用户限制为 3 个选项:
小提琴:http://jsfiddle.net/2GrYk/
This would limit the user to 3 options:
Fiddle: http://jsfiddle.net/2GrYk/
这个答案适用于这些情况:
代码:
演示
或者,对于不支持
selectedOptions
的旧浏览器,演示
This answer works in those cases:
Code:
Demo
Or, for old browsers that don't support
selectedOptions
,Demo
使用 jQuery,您可以将一个函数附加到更改事件,并且由于它是多重选择,因此 val() 将是一个数组。您始终可以检查数组的长度,如果其大小是预定义的,则执行某些操作。以下代码演示了如何知道选择了多少个项目。
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.
想通了!这是生成的代码:
感谢大家的帮助!
figured it out! here's the resulting code:
Thanks for all your help guys!
我基本上合并了几个提供的答案,以制作特定于特定 ID 的内容:
Rob
I basically merged a couple of the provided answers to make something specific to a particular ID:
Rob
你可以使用 jQuery
You can use jQuery
这是一个纯粹的 JavaScript 示例,基于 jilu 的示例。
Here a pure vanilla JavaScript example, based on jilu's example.
瞧!
不需要 Jquery。
吉鲁山
Voila!
No Jquery necessary.
Jilusan