how to select and deselect all options in a select box

前端 未结 5 739
情歌与酒
情歌与酒 2021-02-14 02:02

                        
    
提交评论

  • 2021-02-14 02:35

    You need to add the multiple attribute to the select element, and then you can:

    $('#selectall').click(function() {
        $('select#studentremain option').attr("selected","selected");
    });   
    
    $('#deselectall').click(function() {
        $('select#studentremain option').removeAttr("selected");
    });
    
    0 讨论(0)
  • 2021-02-14 02:35

    Try this demo

    Must add multiple="multiple" in select element

    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");
    });
    
    0 讨论(0)
  • 2021-02-14 02:45

    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

    0 讨论(0)
  • 2021-02-14 02:45

    Most of the answer were outdated, Here selecting and deselecting in two different ways

    $('#selectall').click(function() {
        $("#studentremain option").prop("selected", true);
    });   
    
    $('#deselectall').click(function() {
        $("#studentremain option").val([]);
    });
    
    0 讨论(0)
  • 提交回复
    热议问题