jquerymulti-selectjquery-select2

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


I'm trying to use Select2 jQuery library on MultiSelect control. The controls works fine, but I need to change the default delimiter (separator) of values that select2 uses for Multiselect controls.

Currently output of retrieving the value from multiselect control's value is comma, and I need it to be semi-colon separated values instead, how can this be done?

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


Solution

  • Since you mentioned your option values may contain commas, my original Answer will not work. Try this instead (I've added commas to your option values for demo purposes):

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