如何使用jQuery选择/取消选择选择列表中的所有选项? [英] How does one select/unselect all options in a select List using jQuery?
问题描述
我还不熟悉jQuery,因此很难获得正确的语法. 我试图根据是否选中复选框来一次选择或取消选择一个selectlist元素的所有元素.
I am not yet familiar with jQuery, so it's been difficult to get the syntax correct for this. I'm trying to select or unselect all the elements of a selectlist element, all at once, based on whether a checkbox is checked or not.
我在SO上找到了一些帮助,但是经过大量的查找和测试之后,需要询问社区...
I found some help here at SO, but after a lot of looking and testing, need to ask the community...
在下面的if/else分支中,else分支正常工作:
In the if/else branch below, the else branch works correctly:
if ($('input[name="select_markers"]:checked').length > 0) {
$("#markerlist").prop('selected',true);
} else {
$('form select option').prop('selected',false);
}
但是,这会影响表单中所有不希望的选择元素.我只想影响元素#markerlist,这是我尝试在if分支中执行的操作-但我无法使这一部分正常工作.
However, this affects all the select elements in the form, which I don't want. I only want to affect the element #markerlist, which I am attempting to do in the if branch -- but I cannot get this part to work.
我已经看到了许多其他遍历select元素的示例,但是如果可以的话,我想使这种更简洁的语法起作用.
I've seen many other examples that iterate over a select element, but I'd like to get this cleaner syntax to work, if I can.
TIA, rixter
TIA, rixter
推荐答案
我建议:
$('input[name="select_markers"]').change(
function(){
if ($(this).is(':checked')){
$('#markerlist').find('option').prop('selected','selected')
}
else {
$('#markerlist').find('option').prop('selected',false)
}
});
这篇关于如何使用jQuery选择/取消选择选择列表中的所有选项?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!