我在网上找到了清除表单的代码,但它没有用于选择框的内容。使用 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());
}
});
};
我使用以下代码片段来实现此目的:
$(this).val($(this).find('option[selected]').val());
option[selected]
将获得“硬编码”选定的选项(默认)。option:selected
相反,将获取当前选定的选项。
这适用于单选,多选需要不同的方法:
$(this).find('option').each(function(i, opt) {
opt.selected = opt.defaultSelected;
});
这也适用于单选。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)