我在网上找到了清除表单的代码,但它没有用于选择框的代码。使用 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;
});
这也适用于单选。
关于jquery - 在 HTML 选择标签中查找默认选择的选项?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3849505/