如何使用 jQuery 重置选择元素
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10502093/
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
How to reset a select element with jQuery
提问by Itay Moav -Malimovka
I have
我有
<select id="baba">
<option>select something</option>
<option value="1">something 1</option>
<option value=2">something 2</option>
</select>
Using jQuery, what would be the easiest (less to write) way to reset the select
so the first option is selected?
使用jQuery,重置select
第一个选项的最简单(较少编写)方法是什么?
回答by Bibin Velayudhan
Try this. This will work. $('#baba').prop('selectedIndex',0);
尝试这个。这将起作用。$('#baba').prop('selectedIndex',0);
Check here http://jsfiddle.net/bibin_v/R4s3U/
回答by karim79
回答by Roko C. Buljan
$('#baba option:first').prop('selected',true);
Nowadays you best use .prop(): http://api.jquery.com/prop/
现在你最好使用.prop():http: //api.jquery.com/prop/
回答by Selvakumar Arumugam
回答by serviom
$('#baba').prop('selectedIndex',-1);
回答by Sjoerd Linders
Reset single select field to default option.
将单个选择字段重置为默认选项。
<select id="name">
<option>select something</option>
<option value="1" >something 1</option>
<option value="2" selected="selected" >Default option</option>
</select>
<script>
$('name').val( $('name').find("option[selected]").val() );
</script>
Or if you want to reset all form fields to the default option:
或者,如果您想将所有表单字段重置为默认选项:
<script>
$('select').each( function() {
$(this).val( $(this).find("option[selected]").val() );
});
</script>
回答by Thulasiram
$('#baba option:first').attr('selected',true);
回答by Sebastian Td
The best javascript solution I've found is this
我找到的最好的 javascript 解决方案是这个
elm.options[0].selected="selected";
回答by Junaid Anwar
If you don't want to use the first option (in case the field is hidden or something) then the following jQuery code is enough:
如果您不想使用第一个选项(以防该字段被隐藏或其他内容),那么以下 jQuery 代码就足够了:
$(document).ready(function(){
$('#but').click(function(){
$('#baba').val(false);
})
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.0.2/jquery.min.js"></script>
<select id="baba">
<option>select something</option>
<option value="1">something 1</option>
<option value=2">something 2</option>
</select>
<input type="button" id="but" value="click">
回答by Mohamad Hamouday
This function should work for all types of select (multiple, select, select2):
这个函数应该适用于所有类型的选择(multiple、select、select2):
$.fn.Reset_List_To_Default_Value = function()
{
$.each($(this), function(index, el) {
var Founded = false;
$(this).find('option').each(function(i, opt) {
if(opt.defaultSelected){
opt.selected = true;
Founded = true;
}
});
if(!Founded)
{
if($(this).attr('multiple'))
{
$(this).val([]);
}
else
{
$(this).val("");
}
}
$(this).trigger('change');
});
}
To use it just call:
要使用它,只需调用:
$('select').Reset_List_To_Default_Value();