如何检查select2.js是否至少选择了一个选项?
下面的代码显示消息“请在列表中选择至少一个项目”。即使选择了一个项目。
$('form.validate-form').validator({
disable: false
});
$( "select.validate" ).each(function() {
$(this).validator();
$(this).get(0).setCustomValidity('Please select at least one item in the list.');
});
如何发出消息'请在列表中选择至少一个项目'。选择至少一个选项后消失?
我正在使用Bootstrap验证器插件。
答案 0 :(得分:0)
有点像这样
<!DOCTYPE html>
<head>
<meta charset="utf-8">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css">
<link rel="stylesheet" href="https://ajax.googleapis.com/ajax/libs/jqueryui/1.11.4/themes/smoothness/jquery-ui.css">
<script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.11.4/jquery-ui.min.js"></script>
<link rel="stylesheet" href="//maxcdn.bootstrapcdn.com/font-awesome/4.3.0/css/font-awesome.min.css">
<link href="//cdnjs.cloudflare.com/ajax/libs/select2/4.0.0/css/select2.min.css" rel="stylesheet" />
<script src="//cdnjs.cloudflare.com/ajax/libs/select2/4.0.0/js/select2.min.js"></script>
<script src="http://ajax.aspnetcdn.com/ajax/jquery.validate/1.12.0/jquery.validate.min.js" type="text/javascript"></script>
<style>
.mySelect {
width: 300px;
}
</style>
</head>
<body>
<form id="myform">
<select multiple="true" class="mySelect" name="item" required>
<option value="AL">Alabama</option>
<option value="Am">Amalapuram</option>
<option value="An">Anakapalli</option>
<option value="Ak">Akkayapalem</option>
<option value="WY">Wyoming</option>
</select>
<input type="submit" name='submit' value="Submit">
</form>
<script>
$(document).ready(function() {
$(".mySelect").select2();
$("#myform").validate(
{
rules:
{
item:
{
required: true
}
}
});
});
</script>
</body>
</html>