在HTML选择标签中查找默认选择的选项? [英] Find default selected option in HTML select tag?
问题描述
我在网上找到代码来清除表单,但它对于选择框没有任何作用。使用jquery,我尝试添加代码以在重置表单时在选择框中选择默认选项。我想通过查找默认的唯一方法是查找SELECTED选项的位置。然后我发现当用户选择了其他的东西时,jquery没有看到默认选择,但是关于用户选择的新选项。
我如何找到默认选项在表格中,我可以正确地清除它?
//http://www.learningjquery.com/2007/08/清空表格数据
$ .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'){
// alert($('option',this).size());
alert( $('option [selected]',this).val());
}
});
};
通常 < select>
中的第一个< option>
,所以您可以这样做:
$(this).find(option:first)。attr(selected,true);
尽管如果您要重置整个表单,您可以将其重置为页面上的内容加载一个 .reset()
调用,如下所示:
if (tag =='form')
this.reset();
我不确定那就是您真正的 ,但只是扔在那里。通常,本地DOM方法已经非常方便,不要忽视它们!
I found code online to clear a form but it had nothing for a select box. With jquery i tried adding code to select the default option in the select box when i reset the form. I figured the only way to find the default was to look for where the SELECTED option was. I then discovered when the user selects something else jquery does not see selected as the default but as to the new option the user selected.
How do i get find the default option in the form so i can clear this properly?
//http://www.learningjquery.com/2007/08/clearing-form-data
$.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') {
//alert($('option', this).size());
alert($('option[selected]', this).val());
}
});
};
Usually the default is the first <option>
in the <select>
, so you can do that:
$(this).find("option:first").attr("selected", true);
Though, if you're resetting an entire form, you can reset it to what it was on page load with a .reset()
call, like this:
if (tag == 'form')
this.reset();
I'm not sure that's what you're really after, but just throwing it out there. Often the native DOM methods already there are very handy, don't ignore them!
这篇关于在HTML选择标签中查找默认选择的选项?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!