我如何通过jQuery传递它的ID来获得一个选择的所有选项?
我只是想获取它们的值,而不是文本。
我如何通过jQuery传递它的ID来获得一个选择的所有选项?
我只是想获取它们的值,而不是文本。
当前回答
我发现它既简短又简单,并且可以在Dev Tool控制台本身进行测试。
$ (" # id选项”)。Each ((index,element)=>console.log(index: ${index},值:${element. log)Value}, text: ${element.text})
其他回答
$("#id option").each(function()
{
$(this).prop('selected', true);
});
不过,正确的方法是设置元素的DOM属性,如下所示:
$("#id option").each(function(){
$(this).attr('selected', true);
});
这是一个简单的jQuery脚本:
var items = $("#IDSELECT > option").map(function() {
var opt = {};
opt[$(this).val()] = $(this).text();
return opt;
}).get();
var selectvalues = [];
for(var i = 0; i < items.length; i++) {
for(key in items[i]) {
var id = key;
var text = items[i][key];
item = {}
item ["id"] = id;
item ["text"] = text;
selectvalues.push(item);
}
}
console.log(selectvalues);
copy(selectvalues);
<select>
<option value="volvo">Volvo</option>
<option value="saab">Saab</option>
<option value="mercedes">Mercedes</option>
<option value="audi">Audi</option>
</select>
这将把#myselectbox的选项值放入一个整洁的数组中:
// First, get the elements into a list
var options = $('#myselectbox option');
// Next, translate that into an array of just the values
var values = $.map(options, e => $(e).val())
捷径
$(() => {
$('#myselect option').each((index, data) => {
console.log(data.attributes.value.value)
})})
or
export function GetSelectValues(id) {
const mData = document.getElementById(id);
let arry = [];
for (let index = 0; index < mData.children.length; index++) {
arry.push(mData.children[index].value);
}
return arry;}
对于多选选项:
$('#test').val()返回所选值列表。 $(" #测试选项”)。Length返回选项总数(包括选中的和未选中的)