How to separate data val with a comma

Viewed 129

I have created a select2 field that changes an input field's value to the selected options.

I get it to shop correctly when I select it but the selected are not separated by a comma need help please

$(function() {
  // turn the element to select2 select style
  $('.select2').select2({
    placeholder: "Select a state",
    maximumSelectionLength: 2,
    tokenSeparators: [',', ' ', ';'],
    allowClear: true,
  }).on('change', function(e) {      
    var data = $(".select2 option:selected").text();
    $("#test").val(data + ',');
    
  });
});
<link href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.4/css/select2.min.css" rel="stylesheet" />
<script src="//code.jquery.com/jquery-2.2.4.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.4/js/select2.min.js"></script>

<p>
  <select class="select2" style="width:300px" multiple>
    <option value="AL">Alabama</option>
    <option value="VT">Vermont</option>
    <option value="VA">Virginia</option>
    <option value="WV">West Virginia</option>
  </select>
</p>

<input type="text" id="test">

see example https://jsfiddle.net/eszv1c47/

1 Answers

In order to comma separate the values (with .join(",") you need to get the option texts as an array.

One option is to use jquery's .map() to loop through each selected option and return its text in an array.

With no other changes, your code

    var data = $(".select2 option:selected").text();
    $("#test").val(data + ',');

should be

    var data = $(".select2 option:selected").map((i,e) => $(e).text().trim()).toArray();
    $("#test").val(data.join(','));

Updated fiddle (with select2 fixed) https://jsfiddle.net/u7zevh3g/

$(function() {
  // turn the element to select2 select style
  $('.select2').select2({
    placeholder: "Select a state",
    maximumSelectionLength: 2,
    tokenSeparators: [',', ' ', ';'],
    allowClear: true,
  }).on('change', function(e) {
    var data = $(".select2 option:selected").map((i,e) => $(e).text()).toArray();
    $("#test").val(data.join(','));
  });
});
<link href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.4/css/select2.min.css" rel="stylesheet" />
<script src="//code.jquery.com/jquery-2.2.4.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.4/js/select2.min.js"></script>

<p>
    <select  class="select2" style="width:300px" multiple>
        <option value="AL">Alabama</option>
        <option value="VT">Vermont</option>
        <option value="VA">Virginia</option>
        <option value="WV">West Virginia</option>
    </select>
</p>

<input type="text" id="test">

Related