Javascript 重置选择框的值
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/12737528/
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
Reset the Value of a Select Box
提问by OneChillDude
I'm trying to reset the value of two select fields, structured like this,
我正在尝试重置两个选择字段的值,结构如下,
<select>
<option></option>
<option></option>
<option></option>
</select>
<select>
<option></option>
<option></option>
<option></option>
</select>
jQuery,
jQuery,
$('select').each(function(idx, sel) {
$(sel).find('option :eq(0)').attr('selected', true);
});
Unfortunately, no matter how many ways I try it, it just doesn't happen. Nothing in the console. I have no idea what's going on? I know there has to be a way to do this, you can do anythingwith JS
不幸的是,无论我尝试多少种方法,它都不会发生。控制台中没有任何内容。我不知道是怎么回事?我知道必须有办法做到这一点,你可以用 JS做任何事情
EDIT:
编辑:
I figured out that the issue only occurs when I try to fire the code on the click of a dom element, however, I know that the code should be working, because when I have
我发现该问题仅在我尝试在单击 dom 元素时触发代码时才会发生,但是,我知道代码应该可以正常工作,因为当我有
$('p').click(function(){
console.log('test');
});
It outputs 'test' to the console, but when I include the code in this function, nothing happens. Why is this?
它向控制台输出“test”,但是当我在这个函数中包含代码时,什么也没有发生。为什么是这样?
回答by RobG
I presume you only want to reset a single element. Resetting an entire form is simple: call its resetmethod.
我想你只想重置一个元素。重置整个表单很简单:调用它的reset方法。
The easiest way to "reset" a select element is to set its selectedIndex
property to the default value. If you know that no option is the default selected option, just set the select elemen'ts selectedIndexproperty to an appropriate value:
“重置”选择元素的最简单方法是将其selectedIndex
属性设置为默认值。如果您知道没有选项是默认选择的选项,只需将 select 元素selectedIndex属性设置为适当的值:
function resetSelectElement(selectElement) {
selecElement.selectedIndex = 0; // first option is selected, or
// -1 for no option selected
}
However, since one option may have the selected attribtue or otherwise be set to the default selected option, you may need to do:
但是,由于一个选项可能具有选定属性或以其他方式设置为默认选定选项,您可能需要执行以下操作:
function resetSelectElement(selectElement) {
var options = selectElement.options;
// Look for a default selected option
for (var i=0, iLen=options.length; i<iLen; i++) {
if (options[i].defaultSelected) {
selectElement.selectedIndex = i;
return;
}
}
// If no option is the default, select first or none as appropriate
selectElement.selectedIndex = 0; // or -1 for no option selected
}
And beware of setting attributes rather than properties, they have different effects in different browsers.
并注意设置属性而不是属性,它们在不同的浏览器中具有不同的效果。
回答by neRok
Further to @RobG's pure / vanilla javascript answer, you can reset to the 'default' value with
除了@RobG 的纯/vanilla javascript 答案之外,您可以使用以下命令重置为“默认”值
selectElement.selectedIndex = null;
It seems -1 deselects all items, null selects the default item, and 0 or a positive number selects the corresponding index option.
好像 -1 取消选择所有项,null 选择默认项,0 或正数选择相应的索引选项。
Options in a select object are indexed in the order in which they are defined, starting with an index of 0.
选择对象中的选项按定义的顺序编入索引,从索引 0 开始。
回答by AndyLovesRuby
neRoktouched on this answer above and I'm just expanding on it.
neRok在上面提到了这个答案,我只是在扩展它。
According to the slightly dated, but handy O'Reilly reference book, Javascript: The Definitive Guide:
根据稍微过时但方便的 O'Reilly 参考书Javascript: The Definitive Guide:
The selectedIndexproperty of the Select object is an integer that specifies the index of the selected option within the Select object. If no option is selected, selectedIndexis -1.
Select 对象的selectedIndex属性是一个整数,用于指定 Select 对象中所选选项的索引。如果未选择任何选项,则selectedIndex为 -1。
As such, the following javascript code will "reset" the Select object to no options selected:
因此,以下 javascript 代码会将 Select 对象“重置”为未选择任何选项:
select_box = document.getElementById("myselectbox");
select_box.selectedIndex = -1;
Note that changing the selection in this way does not trigger the onchange()event handler.
请注意,以这种方式更改选择不会触发onchange()事件处理程序。
回答by ORCA Project
What worked for me was:
对我有用的是:
$('select option').each(function(){$(this).removeAttr('selected');});
回答by Hristo
I found a little utility function a while back and I've been using it for resetting my form elements ever since (source: http://www.learningjquery.com/2007/08/clearing-form-data):
不久前我发现了一个小实用函数,从那时起我就一直使用它来重置我的表单元素(来源:http: //www.learningjquery.com/2007/08/clearing-form-data):
function clearForm(form) {
? // iterate over all of the inputs for the given form element
? $(':input', form).each(function() {
? ? var type = this.type;
? ? var tag = this.tagName.toLowerCase(); // normalize case
? ? // it's ok to reset the value attr of text inputs,
// password inputs, and textareas
? ? if (type == 'text' || type == 'password' || tag == 'textarea')
? ? ? this.value = "";
? ? // checkboxes and radios need to have their checked state cleared
// but should *not* have their 'value' changed
? ? else if (type == 'checkbox' || type == 'radio')
? ? ? this.checked = false;
? ? // select elements need to have their 'selectedIndex' property set to -1
? ? // (this works for both single and multiple select elements)
? ? else if (tag == 'select')
? ? ? this.selectedIndex = -1;
? });
};
... or as a jQuery plugin...
...或作为 jQuery 插件...
$.fn.clearForm = function() {
? return this.each(function() {
? ? var type = this.type, tag = this.tagName.toLowerCase();
? ? if (tag == 'form')
? ? ? return $(':input',this).clearForm();
? ? if (type == 'text' || type == 'password' || tag == 'textarea')
? ? ? this.value = '';
? ? else if (type == 'checkbox' || type == 'radio')
? ? ? this.checked = false;
? ? else if (tag == 'select')
? ? ? this.selectedIndex = -1;
? });
};