gpt4 book ai didi

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

转载 作者:技术小花猫 更新时间:2023-10-29 11:50:03 24 4
gpt4 key购买 nike

我在允许多项选择的表单中使用了一个选择标签,但我想最多选择 10 个。这可以使用 javascript 或 jquery 吗?

提前致谢!

最佳答案

这里有一些完整的代码供您使用...一定会喜欢 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

关于javascript - 如何限制在 html 选择框中选择的选项?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2046205/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com