How to unselect options in select using jquery

守給你的承諾、 提交于 2021-02-08 13:59:16

问题


Below is my HTML. I have given multiple option elements in the select tag.

<select class="car" multiple size="3">
    <option value="volvo">Volvo</option>
    <option value="saab">Saab</option>
    <option value="opel">Opel</option>
    <option value="audi">Audi</option>
</select>

I am able to multi-select by holding the CTRL key. I am able to retrieve the selected values using the following jQuery

$.each($(".car option:selected"), function() {
    countries.push($(this).val());
});

How can I unselect the value using jQuery? The selected value will be highlighted as shown:

Thanks in advance


回答1:


Set the selected property to false: $(selector).prop('selected', false).

I have added a button and attached a click event to be able to demonstrate.

var countries = [];

function unselect() {
    $.each($(".car option:selected"), function () {
        countries.push($(this).val());
        $(this).prop('selected', false); // <-- HERE
    });
}

$("#unselect").click(unselect);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<select class="car" multiple size="3">
    <option value="volvo">Volvo</option>
    <option value="saab">Saab</option>
    <option value="opel">Opel</option>
    <option value="audi">Audi</option>
</select>

<input type="button" value="unselect" id="unselect" />



回答2:


You can use $('.car').val([]); for unselect all options in multi-select dropdown.

For multi select value you can pass empty array for unselect all options.

$(document).ready(function(){
  $("#select").click(function(){
    var values= [];
    $(".car > option").each(function(){
    	values.push($(this).attr('value'));
    });
    $('.car').val(values);
  });
  
  $("#unselect").click(function(){
    $('.car').val([]);
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
 <select class="car" multiple size="3">
  <option value="volvo" selected>Volvo</option>
  <option value="saab" selected>Saab</option>
  <option value="opel">Opel</option>
  <option value="audi">Audi</option>
  </select>
  <button id="select">Select All</button>
  <button id="unselect">Unselect All</button>
  </button>


来源:https://stackoverflow.com/questions/39245967/how-to-unselect-options-in-select-using-jquery

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!