Quick way to clear all selections on a multiselect enabled <select> with jQuery?

百般思念 提交于 2019-11-27 03:02:19

问题


Do I have to iterate through ALL the and set remove the 'selected' attribute or is there a better way?


回答1:


Simply find all the selected <option> tags within your <select> and remove the selected attribute:

$("#my_select option:selected").removeAttr("selected");

As of jQuery 1.6, you should use .prop instead of removing the attribute:

$("#my_select option:selected").prop("selected", false);



回答2:


In order to clear all selection, I am using like this and its working fine for me. here is the script:

 $("#ddlMultiselect").multiselect("clearSelection");

 $("#ddlMultiselect").multiselect( 'refresh' );



回答3:


Shortest and quickest way to remove all the selection, is by passing empty string in jQuery .val() function :

$("#my_select").val('')



回答4:


This is the best way to clear a multi-select or list box:

 $("#drp_assign_list option[value]").remove();



回答5:


jQuery's :selected selector is probably what you are looking for.




回答6:


In JQuery:

  $("#id option:selected").prop("selected", false);
  $("#id").multiselect('refresh');



回答7:


In javascript,

You can use the list of all options of multiselect dropdown which will be an Array.Then loop through it to make Selected attributes as false in each Objects.

for(var i=0;i<list.length;i++)
{
   if(list[i].Selected==true)
    {
       list[i].Selected=false;
    }
}



回答8:


You can pass an empty array to unselect all the selection. Here goes an example. From documentation

val() allows you to pass an array of element values. This is useful when working on a jQuery object containing elements like , , and s inside of a . In this case, the inputs and the options having a value that matches one of the elements of the array will be checked or selected while those having a value that doesn't match one of the elements of the array will be unchecked or unselected, depending on the type.

$('.clearAll').on('click', function() {
  $('.dropdown').val([]);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

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

<button class='clearAll'>Clear All Selection</button>



回答9:


$('.selectpicker').selectpicker('deselectAll');

https://developer.snapappointments.com/bootstrap-select/methods/




回答10:


Assuming you are using Bootstrap multiselect dropdown by David Stutz

$('#selectId').multiselect('deselectAll', false);

But for some reason it does not work inside initialization method



来源:https://stackoverflow.com/questions/2254736/quick-way-to-clear-all-selections-on-a-multiselect-enabled-select-with-jquery

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