我在网上找到了一段清除表单的代码,但它并没有针对选择框。使用jquery时,我尝试添加代码,在重置表单时选择选择框中的默认选项。我发现找到默认选项的唯一方法是查找SELECTED选项所在的位置。我随后发现,当用户选择其他选项时,jquery不会将选定的选项视为默认选项,而是视为用户选择的新选项。
我该如何找到表单中的默认选项,以便正确地清除它?
我该如何找到表单中的默认选项,以便正确地清除它?
//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());
}
});
};
.reset()
似乎是你想要的...它会将整个<form>
重置为页面加载时的状态,包括最初选择的<option>
...你的另一种选择是在页面加载时存储它并稍后恢复。 - Nick Craver$("form")[0].reset();
但是将$("form")[0]
替换为$(this)
和$(this).get()
会出现错误。在Chrome中使用 "Uncaught TypeError: Object [object HTMLFormElement] has no method 'reset'"。 - user34537this
是一个表单元素,只需使用this.reset()
即可...希望这个例子能够解决问题:$("form").each(fuction() { this.reset(); });
- Nick Craver