如何将select2多选控件的分隔符更改为分号?

时间:2016-09-14 19:55:34

标签: jquery multi-select select2

我试图在MultiSelect控件上使用Select2 jQuery库。控件工作正常,但我需要更改select2用于Multiselect控件的值的默认分隔符(分隔符)。

目前从多选控件值中检索值的输出为comma,我需要将其作为semi-colon个分隔值,这怎么可以呢?



$("#btn").click(function(e) {
  e.preventDefault();

  $("#result").text('Output: ' + $("#example1").select2("val"));
});

$("#example1").select2({
  seperator: ";"
});

#btn {
  margin: 20px 0px;
}
#result {
  margin: 20px 0px;
}

<link href="https://cdnjs.cloudflare.com/ajax/libs/select2/3.5.4/select2.css" rel="stylesheet" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/select2/3.5.4/select2.js"></script>

<select id="example1" placeholder="Select ..." class="" style="width:100%;" multiple="multiple">
  <option value="Option 1">Option 1</option>
  <option value="Option 2">Option 2</option>
  <option value="Option 3">Option 3</option>
  <option value="Option 4">Option 4</option>
  <option value="Option 5">Option 5</option>
  <option value="Option 6">Option 6</option>
</select>
<input type="button" id="btn" value="Click Me" />
<div id="result">Output:
</div>
&#13;
&#13;
&#13;

1 个答案:

答案 0 :(得分:1)

由于您提到您的选项值可能包含逗号,因此我的原始答案将无效。试试这个(为了演示目的,我为你的选项值添加了逗号):

$("#result").text('Output: ' + $("#example1").select2("val").join(';'));


$("#btn").click(function(e) {
  e.preventDefault();
  $("#result").text('Output: ' + $("#example1").select2("val").join(';'));
});

$("#example1").select2();
#btn {
  margin: 20px 0px;
}
#result {
  margin: 20px 0px;
}
<link href="https://cdnjs.cloudflare.com/ajax/libs/select2/3.5.4/select2.css" rel="stylesheet" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/select2/3.5.4/select2.js"></script>

<select id="example1" placeholder="Select ..." class="" style="width:100%;" multiple="multiple">
  <option value="Option, 1">Option 1</option>
  <option value="Option, 2">Option 2</option>
  <option value="Option, 3">Option 3</option>
  <option value="Option, 4">Option 4</option>
  <option value="Option, 5">Option 5</option>
  <option value="Option, 6">Option 6</option>
</select>
<input type="button" id="btn" value="Click Me" />
<div id="result">Output:
</div>