select2验证不是空值发送

时间:2018-03-16 15:28:35

标签: javascript jquery html

我有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;
&#13;
&#13;

1 个答案:

答案 0 :(得分:1)

您正在检查''这是一个字符串空间,我相信#examplenull作为默认值。

只需检查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>