更改后如何设置下拉列表的默认值?

新手上路,请多包涵

我在 html 页面上有一个下拉菜单,当它第一次加载时,它被设置为默认值。但是当用户更改值时,我希望能够通过单击按钮将下拉列表设置回原始默认值。

我怎样才能做到这一点?没有在隐藏字段中保留原始值的副本。它就像 javascript 重置表单的功能一样。但我只是希望它只适用于下拉列表。

谢谢

原文由 user2206329 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 395
1 个回答

考虑到你有一个简单的选择框..你可以使用 val() 来设置选项..

 <select id="selectId">
<option value="0">Default Value</option>
<option value="1">1</option>
<option value="2">2</option>
</select>
<input type="button" id="buttonID" value="change"/>

试试这个

$('#buttonID').click(function(){
    $('#selectId').val('0'); //value of your default option
});

在这里摆弄

但是,如果您的默认选项是 disabled ,那么您需要变通才能进行分配。有点像这样:

 $(document).on('click', '#buttonID', function(e) {
    var d = $('#selectId option:disabled').prop('disabled', '');
    $('#selectId').val(0);
    d.prop('disabled', 'disabled');
});

jsFiddle

请记住,您可以更改 $('#selectId').val(0); 的值以满足您自己的需要。例如,如果第三个选项是您的默认选项并且值为“bob”,那么您可以说 $('#selectId').val('bob');

我提供的答案只是一个最简单的解决方案…@SpYk3HH 修改了它,如果您默认选择被禁用…是的,@Felix Kling 已经在上一篇 文章 中回答了这个问题,所以看看…无论如何谢谢大家。 .:)


通过 jQuery 使用 Attribute for Cross Compat 的解决方案

为了进一步了解 FelixKling 的解决方案,这里是完整的 jQuery 版本,它使用从原始属性中提取的 .attr 而不是从 .prop 中“更改的属性”。

 $(document).on('click', '#buttonID', function(e) {
        $('#selectID option').filter(function(i){ return this.hasAttribute('selected') }).prop('selected', 'selected')
});

jsFiddle 示例


组合破坏者

要进一步巩固解决方案,请尝试组合使用上述两种方法。这样,无论 HTML 布局如何,您都必须重置为默认值。我的意思是,也许您没有设置默认值的选择框,而是选项 1 是加载时的默认值。同时,其他选择确实有一个默认设置。下面将同时解决这两个问题。

 //    simply a jQuery 1.7+ way of delegating events to any Element match selector
$(document).on('click', 'button', function(e) {
    //    This both selects the first option of a select as well as looks for an option that might have had a default setting
    var opt = $('select').val(0).children('option').filter(function(i){ return this.hasAttribute('selected') });
    //    if opt.length is 0, this will do nothing and option 1 is already set, else this will set this default option to selected
    opt.prop('selected', 'selected');
    // if you have an expected event tied to the select's "change" event, you might fire it here, like so:
    $('select').change();
});

w/Out Comments,漂亮而简短

$(document).on('click', 'button', function(e) {
    var opt = $('select').val(0).children('option').filter(function(i){ return this.hasAttribute('selected') });
    opt.prop('selected', 'selected');
});

示例 1

示例 2(带有更改事件)

原文由 bipen 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题