使用 jquery 清除选择
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6108509/
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
clearing select using jquery
提问by user517406
Is it possible to clear the contents of a html select object using JQuery? I have a function that gets a list to populate the select and appends it to the select, so I need some way of clearing the previous data before appending.
是否可以使用 JQuery 清除 html 选择对象的内容?我有一个函数可以获取一个列表来填充选择并将其附加到选择中,所以我需要某种方式在附加之前清除以前的数据。
回答by diEcho
use .empty()
用 .empty()
$('select').empty().append('whatever');
you can also use .html()
but note
您也可以使用.html()
但请注意
When
.html()
is used to set an element's content, any content that was in that element is completely replaced by the new content. Consider the following HTML:
当
.html()
用于设置元素的内容时,该元素中的任何内容都将被新内容完全替换。考虑以下 HTML:
alternative:--- If you want only option elements to-be-remove, use .remove()
替代方案:---如果您只想删除选项元素,请使用.remove()
$('select option').remove();
回答by alex
回答by xlttj
$('option', '#theSelect').remove();
回答by roblem
Assuming a list like below - and assuming some of the options were selected ... (this is a multi select, but this will also work on a single select.
假设一个列表如下 - 并假设选择了一些选项......(这是一个多选,但这也适用于单个选择。
<select multiple='multiple' id='selectListName'>
<option>1</option>
<option>2</option>
<option>3</option>
<option>4</option>
</select>
In some function called based on some event, the following code would clear all selected options.
在基于某个事件调用的某些函数中,以下代码将清除所有选定的选项。
$("#selectListName").prop('selectedIndex', -1);
$("#selectListName").prop('selectedIndex', -1);
回答by antoniom
回答by Developing
For most of my select options, I start off with an option that simply says 'Please Select' or something similar and that option is always disabled. Then whenever you want to clear your select/option's you can do just do something like this.
对于我选择的大多数选项,我从一个简单地说“请选择”或类似内容的选项开始,并且该选项始终处于禁用状态。然后每当你想清除你的选择/选项时,你可以做这样的事情。
Example
例子
<select id="mySelectOption">
<option value="" selected disabled>Please select</option>
</select>
Answer
回答
$('#mySelectOption').val('Please Select');
回答by Tithira
You may have select option values such as "Choose option". If you want to keep that value and clear the rest of the values you can first remove all the values and append
"Choose Option"
您可能有选择选项值,例如“选择选项”。如果您想保留该值并清除其余值,您可以先删除所有值并append
“选择选项”
<select multiple='multiple' id='selectName'>
<option selected disabled>Choose Option</option>
<option>1</option>
<option>2</option>
<option>3</option>
</select>
Jquery
查询
$('#selectName option').remove(); // clear all values
$('#selectName ').append('<option selected disabled>Choose Option</option>'); //append what you want to keep