将选择值重置为默认值

IT技术 javascript jquery html
2021-02-13 08:49:46

我有选择框

<select id="my_select">
    <option value="a">a</option>
    <option value="b" selected="selected">b</option>
    <option value="c">c</option>
</select>

<div id="reset">
    reset
</div>

我也有重置按钮,这里默认(选定)值为“b”,假设我选择“c”并且在我需要将选择框值重置为默认值后,如何使用 jquery 进行设置?

$("#reset").on("click", function () {
    // What do here?
});

jsfiddle:http : //jsfiddle.net/T8sCf/1/

6个回答

您可以使用defaultSelected选项元素属性

包含selectedHTML 属性的初始值,表示该选项是否被默认选中。

因此,DOM 界面已经跟踪最初选择了哪个选项。

$("#reset").on("click", function () {
    $('#my_select option').prop('selected', function() {
        return this.defaultSelected;
    });
});

演示

这甚至适用于多选元素。

如果您不想遍历所有选项,而是在找到最初选择的选项后“中断”,则可以.each改用:

$('#my_select option').each(function () {
    if (this.defaultSelected) {
        this.selected = true;
        return false;
    }
});

没有 jQuery:

var options = document.querySelectorAll('#my_select option');
for (var i = 0, l = options.length; i < l; i++) {
    options[i].selected = options[i].defaultSelected;
}
使用defaultSelected属性设置默认选项元素并像这样重置$('#select option').removeAttr('selected');
2021-03-29 08:49:46
$('#my_select').get(0).selectedIndex = 1;

但是,在我看来,更好的方法是仅使用 HTML(带有<input type="reset" />):

<form>
    <select id="my_select">
        <option value="a">a</option>
        <option value="b" selected="selected">b</option>
        <option value="c">c</option>
    </select>
    <input type="reset" value="reset" />
</form>
@ChamikaSandamal.get(0)用于获取 DOM 元素,以便您可以访问诸如.selectedIndex
2021-03-27 08:49:46
代替$('#my_select').get(0),我们还可以使用$('#my_select')[0]-更快的打字。
2021-04-03 08:49:46
get(0)ID什么理由选择器一起使用吗?
2021-04-04 08:49:46
@ChamikaSandamal 不,只是快速打字。
2021-04-05 08:49:46
$("#reset").on("click", function () {
    $("#my_select").val('b');//Setting the value as 'b'
});
我不知道高级选择框中的默认值是什么
2021-03-20 08:49:46
它没有重置,我认为是它的设置。
2021-03-23 08:49:46
@OTARIKI - 如果您事先不知道默认值是什么,您怎么知道将selected="selected"属性添加到哪个选项?!
2021-03-27 08:49:46
@Jamiec:可以,但不一定会生成 JavaScript。
2021-04-07 08:49:46
是的,所以服务器端您仍然可以生成知道默认值的客户端代码!
2021-04-12 08:49:46

为什么不使用一个简单的 javascript 函数并在 onclick 事件上调用它呢?

function reset(){
document.getElementById("my_select").selectedIndex = 1; //1 = option 2
}
'1 = option 2' 是什么意思?
2021-04-03 08:49:46
JS 从 0 开始计算所选的 indeces。第一个选择的选项将是 selectedIndex = 0,第二个选项 = 1,第三个选项 = 2,等等。
2021-04-11 08:49:46

您可以使用元素data属性select

<select id="my_select" data-default-value="b">
    <option value="a">a</option>
    <option value="b" selected="selected">b</option>
    <option value="c">c</option>
</select>

你的 JavaScript,

$("#reset").on("click", function () {
    $("#my_select").val($("#my_select").data("default-value"));
});

http://jsfiddle.net/T8sCf/10/

更新


如果您不知道默认选择并且无法更新 html,请在 dom ready 中添加以下代码,

$("#my_select").data("default-value",$("#my_select").val());

http://jsfiddle.net/T8sCf/24/

最后,这对我有用,谢谢 [我正在使用 Material Bootstrap]
2021-03-15 08:49:46