将选择值重置为默认值 [英] Reset select value to default
问题描述
我有选择框
< select id =my_select>
< option value =a> a< / option>
< option value =bselected =selected> b< / option>
< option value =c> c< / option>
< / select>
< div id =reset>
重置
< / div>
我也有复位按钮,这里默认(选中)值是b,假设我选择 c后,我需要插入选择框值默认,如何使这个使用jQuery?
$(#reset ).on(click,function(){
//这里有什么?
});
jsfiddle: http://jsfiddle.net/T8sCf/1/
您可以使用的 defaultSelected
属性一个选项元素:
包含所选
的初始值
HTML属性,指示该选项是否被默认选中。
所以,DOM接口已经跟踪选择了哪个选项(click,function(){
$(($#$))$($#$ $ $ '(#'选择'选项')。prop('selected',function(){
return this.defaultSelected;
});
});
这甚至可以用于多选元素。
如果您不想迭代所有选项,但是在找到最初选择的选项之后break,则可以使用 .each
代替: / p>
$('#my_select option')。each(function(){
if(this.defaultSelected){
this.selected = true;
return false;
}
});
没有jQuery:
var options = document.querySelectorAll('#my_select option');
for(var i = 0,l = options.length; i< l; i ++){
options [i] .selected = options [i] .defaultSelected;
}
I have select box
<select id="my_select">
<option value="a">a</option>
<option value="b" selected="selected">b</option>
<option value="c">c</option>
</select>
<div id="reset">
reset
</div>
I have also reset button, here default (selected) value is "b", suppose I select "c" and after I need resert select box value to default, how to make this using jquery?
$("#reset").on("click", function () {
// What do here?
});
jsfiddle: http://jsfiddle.net/T8sCf/1/
You can make use of the defaultSelected
property of an option element:
Contains the initial value of the
selected
HTML attribute, indicating whether the option is selected by default or not.
So, the DOM interface already keeps track which option was selected initially.
$("#reset").on("click", function () {
$('#my_select option').prop('selected', function() {
return this.defaultSelected;
});
});
This would even work for multi-select elements.
If you don't want to iterate over all options, but "break" after you found the originally selected one, you can use .each
instead:
$('#my_select option').each(function () {
if (this.defaultSelected) {
this.selected = true;
return false;
}
});
Without jQuery:
var options = document.querySelectorAll('#my_select option');
for (var i = 0, l = options.length; i < l; i++) {
options[i].selected = options[i].defaultSelected;
}
这篇关于将选择值重置为默认值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!