我如何通过jQuery传递它的ID来获得一个选择的所有选项?
我只是想获取它们的值,而不是文本。
我如何通过jQuery传递它的ID来获得一个选择的所有选项?
我只是想获取它们的值,而不是文本。
当前回答
$("input[type=checkbox][checked]").serializeArray();
Or:
$(".some_class[type=checkbox][checked]").serializeArray();
看看结果:
alert($("input[type=checkbox][checked]").serializeArray().toSource());
其他回答
您可以根据复选框的名称获取所有“选定值”,并将它们显示在以“,”分隔的字符串中。
一个很好的方法是使用jQuery的$.map():
var selected_val = $.map($("input[name='d_name']:checked"), function(a)
{
return a.value;
}).join(',');
alert(selected_val);
有些答案使用这两种方法,但恕我直言,地图是更好的选择:
$("select#example option").map(function() {return $(this).val();}).get();
jQuery中有(至少)两个地图函数。Thomas Petersen的答案是“Utilities/jQuery.map”;这个答案使用了“遍历/映射”(因此代码更简洁)。
这取决于你要如何处理这些值。如果你想从函数中返回值,map可能是更好的选择。但是,如果您打算直接使用这些值,则可能需要每个值。
$("input[type=checkbox][checked]").serializeArray();
Or:
$(".some_class[type=checkbox][checked]").serializeArray();
看看结果:
alert($("input[type=checkbox][checked]").serializeArray().toSource());
这将把#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())
$("#id option").each(function()
{
$(this).prop('selected', true);
});
不过,正确的方法是设置元素的DOM属性,如下所示:
$("#id option").each(function(){
$(this).attr('selected', true);
});