Reputation: 23
I am trying to convert select2 array to string to be used in form. Currently my output looks like this:
?source%5B%5D=x1&source%5B%5D=x2
i am looking to convert it to have comma separated string. I have tried to use 'string = source.join()' but output of my string is empty.
%5B%5D=x1&source%5B%5D=x2&string=
What I am trying to get is something like this:
string%5B%5D=x1,x2
<form action="/action_page.php">
<select class="form-control select2" multiple="" id="source" name="source[]" style="width: 250px;">
<optgroup label="Group1">
<option>x1</option>
<option>x2</option></optgroup>
<optgroup label="Group2">
<option>y1</option>
<option>y2</option></optgroup>
</select>
<script type="text/javascript">
$(".select2").select2({
tags: true
});
</script>
<script type="text/javascript">
string = source.join()
</script>
<input type='hidden' name='string' ></input>
<br><br>
<input type="submit">
</form>
Upvotes: 0
Views: 1506
Reputation: 2521
I don't know if it's really what you want, but that can give you clues.
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.7/css/select2.min.css" rel="stylesheet" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.7/js/select2.min.js"></script>
<form onsubmit="onFormSubmit()">
<select class="form-control select2" multiple="" id="source" style="width: 250px;">
<optgroup label="Group1">
<option>x1</option>
<option>x2</option>
</optgroup>
<optgroup label="Group2">
<option>y1</option>
<option>y2</option>
</optgroup>
</select>
<script type="text/javascript">
// Init Select2
var mySelect = $(".select2").select2({
tags: true
});
// On form submit
var onFormSubmit = function(){
// Get selected value (only if at least one selected)
if (mySelect.val() !== null && mySelect.val().length > 0) {
var selectedSource = "string=" + mySelect.val().join(',');
alert(selectedSource);
}
}
</script>
<input type='hidden' name='string' />
<br><br>
<input type="submit" />
</form>
Upvotes: 2