gpt4 book ai didi

javascript - 将 Select2 数组输出转换为字符串

转载 作者:行者123 更新时间:2023-12-02 23:27:42 24 4
gpt4 key购买 nike

我正在尝试将 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>

最佳答案

我不知道这是否真的是你想要的,但这可以给你线索。

<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>

关于javascript - 将 Select2 数组输出转换为字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56663005/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com