Javascript 如何使用jQuery清除SELECT输入中的所有选定项目?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4748303/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 13:53:48  来源:igfitidea点击:

How to clear all selected items in a SELECT input using jQuery?

javascriptjqueryhtml

提问by mattruma

I am think this should be fairly easy, but struggling a bit ... I have a SELECTinput element that allows the user to select multiple items. I would like to provide a mechanism for them to clear all selected items, probably will just be a SPANtag or something similar.

我认为这应该相当容易,但有点挣扎......我有一个SELECT输入元素,允许用户选择多个项目。我想为他们提供一种机制来清除所有选定的项目,可能只是一个SPAN标签或类似的东西。

Anyway ... using jQuery, how I would I clear the selection on the SELECTinput element so no items are selected.

无论如何......使用jQuery,我将如何清除SELECT输入元素上的选择,以便没有选择任何项目。

回答by Nick Craver

In the case of a <select multiple>the .val()function takes/returns an array, so you can simply pass in an empty array to clear the selection, like this:

在的情况下<select multiple>.val()函数取/返回的阵列,所以可以在一个空数组简单地传递到清除选择,如下所示:

$("#selectID").val([]);

You can test it out here.

你可以在这里测试一下

回答by roblem

This worked to clear all selected options for me..

这有助于为我清除所有选定的选项。

$("#selectListName").prop('selectedIndex', -1)

The select list looked like

选择列表看起来像

<select multiple='multiple' id='selectListName'> 
  <option>1</option> 
  <option>2</option> 
  <option>3</option> 
  <option>4</option>
</select>

回答by Darmen Amanbayev

Try:

尝试:

$("select option:selected").each(function () {
    $(this).remove(); //or whatever else
});

回答by Steve

Only this worked for me:-

只有这对我有用:-

$("#selectid").find('option').attr("selected",false) ;

回答by Haim Evgi

i try something like

我尝试类似的东西

$("#my-Select").find('option').attr("selected","") ;

回答by Zaki Ahmed

This solution worked for me...

这个解决方案对我有用......

$('#my-Select').val('').trigger('change');

This works on almost any input type.

这适用于几乎所有输入类型。

回答by mbadaro

Try that:

试试看:

$("#selectID").empty();

Worked for me!

为我工作!

回答by Poonam Bhatt

Try this

尝试这个

<select id='select1' ></select>
<input type= 'button' value = 'Clear Selection' id = 'remove' />

$(document).ready(function() {  
   $('#remove').click(function() {  
     return $('#select1 option:selected').remove(); 
   });
 });

回答by Lourens

Maybe 

$('#mySelect option').each(function(i, e)
{
   e.selected = false
});

回答by Hexxefir

Better than this, you can use:

比这更好,您可以使用:

$("#selectID").empty();

That works on almost anything in the DOM.

这几乎适用于 DOM 中的任何内容。