如何选择和取消选择选择框中的所有选项

时间:2013-01-10 14:42:15

标签: jquery html

<select name="remaintextarea" id="studentremain" size="10">
    <option value="one">One</option>
    <option value="two">Two</option>
    <option value="three">Three</option>
</select>

<button type='button' id='selectall'>Select All</button>
<button type='button' id='deselectall'>De-Select All</button>

上面有一个选择框,选择全部并取消选择上面的所有按钮。我的问题是使用jquery,如何点击相关按钮时,如何让按钮选择所有选项并取消选择上面选择框中的所有选项?

下面我只有两个按钮的点击处理程序:

$('#selectall').click(function() {

});   

$('#deselectall').click(function() {

});

5 个答案:

答案 0 :(得分:24)

您需要将multiple属性添加到select元素,然后您可以:

$('#selectall').click(function() {
    $('select#studentremain option').attr("selected","selected");
});   

$('#deselectall').click(function() {
    $('select#studentremain option').removeAttr("selected");
});

答案 1 :(得分:8)

试试这个demo

必须在select元素

中添加multiple =“multiple”

HTML:

<select multiple="multiple" name="remaintextarea" id="studentremain" size="10">
    <option value="one">One</option>
    <option value="two">Two</option>
    <option value="three">Three</option>
</select>
<button type='button' id='selectall'>Select All</button>
<button type='button' id='deselectall'>De-Select All</button>

JS:

$('#selectall').click(function() {
    $('#studentremain > option').attr("selected", "selected");
});   

$('#deselectall').click(function() {
    $('#studentremain > option').removeAttr("selected");
});

答案 2 :(得分:3)

首先将 multiple 属性添加到您的选择框中,以便您可以选择多个值,然后这样就可以了,因为您使用的是jQuery。

//for selection of all.
$('#studentremain option').attr('selected','selected');

//for removal of selection.
$('#studentremain option').removeAttr('selected');

您可以在attr处尝试 prop removeProp

答案 3 :(得分:0)

Somehow the answers above did not work for me. Seems that you have to use properties instead of attributes. Here is the code:

$('#selectall').click(function() {
    $('select#studentremain option').prop("selected",true);
});   

$('#deselectall').click(function() {
    $('select#studentremain option').prop("selected",false);
});

Documentation says that selected attribute only specifies that an option should be pre-selected when the page loads. But is not set when the actual option is selected by the user. Source

答案 4 :(得分:0)

  

大多数答案已经过时,   这里以两种不同的方式选择和取消选择

$('#selectall').click(function() {
    $("#studentremain option").prop("selected", true);
});   

$('#deselectall').click(function() {
    $("#studentremain option").val([]);
});