我正在尝试将select2数组转换为要以形式使用的字符串。目前,我的输出如下所示:
?source%5B%5D = x1&source%5B%5D = x2
我希望将其转换为逗号分隔的字符串。我试图使用'string = source.join()',但是我的字符串输出为空。
%5B%5D = x1&source%5B%5D = x2&string =
我想要得到的是这样的:
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>
答案 0 :(得分:0)
我不知道这是否真的是您想要的,但这可以为您提供线索。
<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" 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">
// 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>