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

How to change select2 multiselect control's delimiter to semi-colon?

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

当前从多选控件的值中检索值的输出是 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>

由于您提到您的选项值可能包含逗号,因此我的原始答案将不起作用。试试这个(出于演示目的,我在您的选项值中添加了逗号):

$("#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>