我在多选
中获取所有选定选项时遇到问题<select multiple="" title="" class="" id="fm_delivery_or_collection" name="fm_fields[fm_delivery_or_collection][]">
<option value="90">Delivery or Collection1</option>
<option value="91">Delivery or Collection2</option>
<option value="92">Delivery or Collection3</option>
</select>
Bellow是我的代码,它只返回我首选的选项
var select = form.find('select')
for (var i = 0; i < select.length; i++)
{
var s_id = jQuery(select[i]).attr('id');
var str="",i;
var e = document.getElementById(s_id);
var strUser = e.options[e.selectedIndex].text;
var name = jQuery(select[i]).attr('name')
var str1 = jQuery(select[i]).attr('id').replace("fm_"," ")
requestString += "<b>"+str1.replace(/_/g," ")+"</b>" + ':' +strUser+"<br>";
}
所以请建议我如何获得所有选择的选项文本以及我犯错的地方?
答案 0 :(得分:32)
您的评论 please suggest me how can i get all selected option text
,So you can try this:
$("#fm_delivery_or_collection option:selected").each(function () {
var $this = $(this);
if ($this.length) {
var selText = $this.text();
console.log(selText);
}
});
答案 1 :(得分:11)
// Return an array of the selected opion values
// select is an HTML select element
function GetSelectValues(select) {
var result = [];
var options = select && select.options;
var opt;
for (var i=0, iLen=options.length; i<iLen; i++) {
opt = options[i];
if (opt.selected) {
result.push(opt.value || opt.text);
}
}
return result;
}
将此功能传递给你的选择框..
var selectBox = document.getElementsById('fm_delivery_or_collection');
alert(GetSelectValues(selectBox ));
它将返回所选值的数组
使用Jquery
$('select#fm_delivery_or_collection').val()
从val
调用的select
函数将返回一个数组,如果它是一个数组。
答案 2 :(得分:8)
现在只需一行即可完成
var text = $('#selector option:selected').toArray().map(item => item.text).join();
它返回如下:
text1,text2,text3,text4
答案 3 :(得分:2)
试试这个
$("#fm_delivery_or_collection option").each(function(){
if($(this).attr('selected') == 'selected')
{
var name = $("#fm_delivery_or_collection").attr('name')
var str1 = $("#fm_delivery_or_collection").attr('id').replace("fm_"," ")
requestString += "<b>"+str1.replace(/_/g," ")+"</b>" + ':' +strUser+"<br>";
}
})
答案 4 :(得分:1)
$("#id :selected").each(function (i,sel) {
alert($(sel).text());
});
希望它有助于......
答案 5 :(得分:0)
$("#selection option:selected").each(function () {
var $this = $(this);
if ($this.length) {
var selText = $this.text();
console.log(selText);
$('#selected').append(selText+', ');
}
});
答案 6 :(得分:0)
只需添加以下代码行:-
var reciever= jQuery('#to_select option:selected').toArray().map(item => item.text).join();
/* alert(reciever); */