使用select2的多重选择元素无法正常工作 [英] Multiple select element using select2 does not work properly

查看:156
本文介绍了使用select2的多重选择元素无法正常工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

请注意,这与具有multiple属性的<select>元素无关,而是表单中的多个<select>,我在这里没有发现.

Please note that this is not about <select> element with multiple attribute, but multiple <select>s in a form, which I haven't found asked here.

参见此 codepen

我有两个具有唯一ID和名称的<select>元素.在这两个元素上,我还使用了select2.我期望两者会启动相同的行为,因此会使用相同的jQuery代码.两者确实启动了select2,但后者没有显示<option>标记中包含的任何选项.它仅显示未找到结果"消息.

I have two <select> element with unique ids and names. On both element I've also used select2. I was expecting the two would have initiated the same behavior hence the same jQuery code. The two did start the select2 but the later was not showing any option included in the <option> tags. It only shows the "No result found" message.

问题:我很确定这是一件很琐碎的事,但是谁能告诉我代码有什么问题吗?应该怎么写?

Question : I am pretty sure this one is pretty trivial, but can anyone show me what is wrong with the code? How is it supposed to be written?

这是html:

<form action="" method="POST" role="form">
  <div class="form-group">
    <label for="">Add Service Name</label>
    <select class="form-control select2" name="test-1" id="number1">
      <option>Service 1</option>
      <option>Service 2</option>
    </select>
  </div>
  <div class="form-group">
    <label for="">Add Service Name</label>
    <select class="form-control select2-service-package" id="number2" name="test-2">
      <option>Service 1</option>
      <option>Service 2</option>
    </select>
  </div>
  <button type="submit" class="btn btn-primary">Create</button>
</form>

这是jQuery代码

  if ($('.select2-service-package').length > 0) {
    $('.select2-service-package').select2();
  };

  if ($('.select2').length > 0) {
    $('.select2').select2();    
  };

推荐答案

尝试将类select2的名称更改为其他名称(例如myselect).

Try to change the name of the class select2 to something else (e.g. myselect).

Select2插件可能在内部使用select2类.

Select2 plugin probably uses the select2 class internally.

工作示例: https://jsfiddle.net/6pnv3v58/

这篇关于使用select2的多重选择元素无法正常工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆