Javascript 将Select2数组输出转换为字符串
我正在尝试将select2数组转换为要在表单中使用的字符串。当前我的输出如下所示: ?源%5B%5D=x1和源%5B%5D=x2 我想把它转换成逗号分隔的字符串。我尝试使用“string=source.join()”,但字符串的输出为空 %5B%5D=x1&源%5B%5D=x2&字符串= 我想要得到的是这样的东西: 字符串%5B%5D=x1,x2Javascript 将Select2数组输出转换为字符串,javascript,html,jquery-select2,Javascript,Html,Jquery Select2,我正在尝试将select2数组转换为要在表单中使用的字符串。当前我的输出如下所示: ?源%5B%5D=x1和源%5B%5D=x2 我想把它转换成逗号分隔的字符串。我尝试使用“string=source.join()”,但字符串的输出为空 %5B%5D=x1&源%5B%5D=x2&字符串= 我想要得到的是这样的东西: 字符串%5B%5D=x1,x2 x1 x2 y1 y2 $(“.select2”)。选择2({ 标签:真的 }); string=source.join() 我不知道这是否真的是
x1
x2
y1
y2
$(“.select2”)。选择2({
标签:真的
});
string=source.join()
我不知道这是否真的是你想要的,但这可以给你一些线索
x1
x2
y1
y2
//初始化选择2
var mySelect=$(“.select2”)。select2({
标签:真的
});
//提交表格
var onFormSubmit=函数(){
//获取选定值(仅当至少选定一个时)
if(mySelect.val()!==null&&mySelect.val().length>0){
var selectedSource=“string=“+mySelect.val().join(',');
警报(选择的来源);
}
}
我不知道这是否真的是你想要的,但这可以给你一些线索
x1
x2
y1
y2
//初始化选择2
var mySelect=$(“.select2”)。select2({
标签:真的
});
//提交表格
var onFormSubmit=函数(){
//获取选定值(仅当至少选定一个时)
if(mySelect.val()!==null&&mySelect.val().length>0){
var selectedSource=“string=“+mySelect.val().join(',');
警报(选择的来源);
}
}
感谢您的输入,但上面给出的输出与前面相同:“source[]=x1&source[]=x2”。我想得到的是:“string=x1,x2”这仍然不是我想要的。您在selectedSource中创建了字符串,但未将其添加到表单中。它通过添加document.getElementById('string')。value=mySelect.val().join(',');谢谢你们两位的帮助!:-)很高兴帮助您好,请问name=“source[]”
用于什么?它是强制性的,需要在HTML中有吗?因为我看不出它在什么地方有用。谢谢。感谢您的输入,但上面给出的输出与前面相同:“source[]=x1&source[]=x2”。我想得到的是:“string=x1,x2”这仍然不是我想要的。您在selectedSource中创建了字符串,但未将其添加到表单中。它通过添加document.getElementById('string')。value=mySelect.val().join(',');谢谢你们两位的帮助!:-)很高兴帮助您好,请问name=“source[]”
用于什么?它是强制性的,需要在HTML中有吗?因为我看不出它在什么地方有用。非常感谢。
<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>