【问题标题】:Set the default value in select list using jQuery使用 jQuery 在选择列表中设置默认值
【发布时间】:2020-08-08 02:52:28
【问题描述】:

如果我的下拉列表中只有一个选项,我需要选择此选项作为默认选项。如何使用 jQuery 做到这一点?

【问题讨论】:

    标签: javascript jquery forms select


    【解决方案1】:

    我认为您是 SO 新手,这里通常的程序是在发布之前提供一些您自己在此问题上的努力的代码。也就是说,这是简单的 JQuery:

    编辑以适应新规范:

    if($("#select_id option").length == 2){ //if there are exactly 2 options in the select element
        $("#select_id option:nth(1)").attr("selected",true); //take the second option (element 0) inside the element with id "select_id" and set the selected attribute.
    } //I think we do not need an else if any other thing will select the first option by default
    

    无论如何,默认情况下应该选择第一个选项。

    <select id="select_id">
        <option value=1>First option is selected by default</option>
    </select>
    <!--adding proof that it is selected-->
    <script>
        $(function(){
             alert($("#select_id").val()); //this will alert 1, since is the value of my first option
        });
    </script>
    

    【讨论】:

    • 我的下拉列表中的选项数量是可变的和动态的。第一个选项是自动选择的,但默认为空。我应该计算选项,如果有 2 个自动选择第二个 ...
    • 要清楚,如果有 3 个,您应该自动选择第 3 个,第 4-> 个,依此类推?
    • 如果有 3 个,您应该自动选择第一个“空字段”。
    • 那么,只有2个,我们才应该自动选择第二个选项?
    • 我想我明白了,现在我修改了代码以仅在有 2 个选项时才选择第二个选项(其他任何事情,什么都不做,所以自动选择第一个)
    猜你喜欢
    • 1970-01-01
    • 2017-03-31
    • 2017-12-08
    • 1970-01-01
    • 2011-06-14
    • 2016-04-10
    • 2011-09-13
    • 1970-01-01
    • 2013-06-02
    相关资源
    最近更新 更多