我有select2
jquery插件,我将其设置为多个选择选项,我想要这个字段,如果没有任何选项选择然后submit
表格并给出消息这个字段是必需的。为什么当字段为空时我点击submit button
并且alert
未显示。任何帮助。
代码
jQuery(function($){
$('#example').select2({
placeholder: 'Select a month'
});
$(".add").click(function(e){
if (jQuery('#example').val() == '') {
alert('this feilds is required');
}
});
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link href="https://rawgit.com/select2/select2/master/dist/css/select2.min.css" rel="stylesheet"/>
<script src="https://rawgit.com/select2/select2/master/dist/js/select2.js"></script>
<select id="example" multiple="multiple" style="width: 300px">
<option value="JAN">January</option>
<option value="FEB">February</option>
<option value="MAR">March</option>
<option value="APR">April</option>
<option value="MAY">May</option>
<option value="JUN">June</option>
<option value="JUL">July</option>
<option value="AUG">August</option>
<option value="SEP">September</option>
<option value="OCT">October</option>
<option value="NOV">November</option>
<option value="DEC">December</option>
</select>
<div>
<button class="add">submit</button>
</div>
&#13;
答案 0 :(得分:1)
您正在检查''
这是一个字符串空间,我相信#example
将null
作为默认值。
只需检查null
。
jQuery(function($){
$('#example').select2({
placeholder: 'Select a month'
});
$(".add").click(function(e){
if (jQuery('#example').val() == null) {
alert('this feilds is required');
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link href="https://rawgit.com/select2/select2/master/dist/css/select2.min.css" rel="stylesheet"/>
<script src="https://rawgit.com/select2/select2/master/dist/js/select2.js"></script>
<select id="example" multiple="multiple" style="width: 300px">
<option value="JAN">January</option>
<option value="FEB">February</option>
<option value="MAR">March</option>
<option value="APR">April</option>
<option value="MAY">May</option>
<option value="JUN">June</option>
<option value="JUL">July</option>
<option value="AUG">August</option>
<option value="SEP">September</option>
<option value="OCT">October</option>
<option value="NOV">November</option>
<option value="DEC">December</option>
</select>
<div>
<button class="add">submit</button>
</div>