在HTML select标签中查找默认选择的选项?

6 html forms jquery

我在网上找到了清除表单的代码,但它对于选择框没有任何帮助.使用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());
        }
    });
};
Run Code Online (Sandbox Code Playgroud)

Kor*_*tor 13

我使用以下代码片段来实现此目的:

$(this).val($(this).find('option[selected]').val());
Run Code Online (Sandbox Code Playgroud)

option[selected]将获得"硬编码"选定选项(默认值). option:selected相反,将获得当前选择的选项.

这适用于单选,多选需要不同的方法:

$(this).find('option').each(function(i, opt) {
    opt.selected = opt.defaultSelected;
});
Run Code Online (Sandbox Code Playgroud)

这也适用于单个选择.


Nic*_*ver 3

通常默认值是<option>中的第一个<select>,因此您可以这样做:

$(this).find("option:first").attr("selected", true);
Run Code Online (Sandbox Code Playgroud)

不过,如果您要重置整个表单,则可以通过调用将其重置为页面加载时的状态.reset(),如下所示:

if (tag == 'form')
  this.reset();
Run Code Online (Sandbox Code Playgroud)

我不确定这就是你真正想要的,但只是把它扔在那里。通常,已经存在的原生 DOM 方法非常方便,不要忽略它们!