简体   繁体   中英

Select2 settings undefined error with jquery.validate

I am using Select2 as my dropdown. I am getting the following error even if I click inside dropdown:

在此处输入图片说明 This error occurs only when I use select2 inside my form, outside the form it is working perfectly.

Here is my code:

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.3/css/select2.min.css" rel="stylesheet" />
    <script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.3/js/select2.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.16.0/jquery.validate.min.js"></script>
    <script src="~/Scripts/jquery.unobtrusive-ajax.min.js"></script>
    <script src="~/Scripts/jquery.validate.unobtrusive.min.js"></script>

<script type="text/javascript">
    $("#ddlUsers").select2();
</script>
<form class="form-horizontal">
    <div class="form-group">
          <label class="col-sm-2 control-label">Add User</label>
          <div class="col-sm-10">
               <select id="ddlUsers" class="form-control" multiple="multiple">
                   <option value="1">1</option>
                    <option value="2">2</option>
                    <option value="3">3</option>
                </select>
           </div>
     </div>
     <div class="form-group">
           <div class="col-sm-offset-2 col-sm-10">
               <button type="button" onclick="onAddclick();return false;" class="btn btn-primary">Add User</button>
            </div>
      </div>
</form>

In the Select2 examples they Use classes to define the selected options have you tried this approach as the jQuery may be using the ID attribute for some thing else.

Also you label usually has the same ID as the input field it is for.

The "Inspect" image shows that the JavaScript/jQuery code generated six (6) errors.

在此处输入图片说明

At least two (2) of the errors were due to a TypeError about "settings". Since this code was not included in the original post, it is difficult to diagnose your problems with the information provided.

Review the error diagnostic information shown by "Inspect" and make the code changes to avoid these errors.

I'm not 100% if it's the case here, but this error can occur when the form contains dynamically added elements, that were not initialised by jQuery.validate .validator (validator property/object was not set). Then, as part of validation process, new element's .validator object's .settings property is accessed, but it's not there. I would suggest trying to run .validate() method on the form, immediately and after addition of any new element to the DOM.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM