代码之家  ›  专栏  ›  技术社区  ›  Amr Elgarhy

如何使用jquery选择下拉列表中的第一个元素?

  •  102
  • Amr Elgarhy  · 技术社区  · 16 年前

    我想知道如何使用jquery选择页面上所有select标记中的第一个选项。

    尝试过:

    $('select option:nth(0)').attr("selected", "selected"); 
    

    但没有工作

    8 回复  |  直到 7 年前
        1
  •  186
  •   Zander    7 年前

    试试这个…

    $('select option:first-child').attr("selected", "selected");
    

    另一种选择是这样,但它一次只能用于一个下拉列表,如下所示:

    var myDDL = $('myID');
    myDDL[0].selectedIndex = 0;
    

    看看这篇关于如何基于值进行设置的文章,它很有趣,但对于这个特定的问题没有帮助:

    Change the selected value of a drop-down list with jQuery

        2
  •  13
  •   Aistina    12 年前

    您的选择器错误,您可能正在查找

    $('select option:nth-child(1)')
    

    这也适用于:

    $('select option:first-child')
    
        3
  •  9
  •   Community CDub    8 年前

    rsolgberg的另一种解决方案,它触发 'onchange' 事件(如果存在):

    $("#target").val($("#target option:first").val());
    

    How to make first option of <select > selected with jQuery?

        4
  •  5
  •   Yuck    12 年前
    $("#DDLID").val( $("#DDLID option:first-child").val() );
    

    For Complete Drop Down List Operations using Jquery

        5
  •  4
  •   RichN    16 年前

    你想要的可能是:

    $("select option:first-child")
    

    这个代码是什么

    attr("selected", "selected");
    

    正在执行的操作是将“选定”属性设置为“选定”

    如果您想要选定的选项,不管它是否是第一个子项,选择器都是:

    $("select").children("[selected]")
    
        6
  •  2
  •   Brandon    8 年前

    我回答是因为以前的回答已经停止使用最新版本的jquery。我不知道它何时停止工作,但文档中说.prop()是自jquery 1.6以来获取/设置属性的首选方法。

    这就是我让它工作的方法(使用jquery 3.2.1):

    $('select option:nth-child(1)').prop("selected", true);
    

    我使用的是knockoutjs,变更绑定没有使用上面的代码触发,所以我在末尾添加了.change()。

    以下是我的解决方案需要的:

    $('select option:nth-child(1)').prop("selected", true).change();
    

    请参见以下文档中的.prop()注释: http://api.jquery.com/prop/

        7
  •  1
  •   sarah    14 年前

    如果要检查所选选项的文本,无论其是否为第一个子选项。

    var a = $("#select_id option:selected").text();
    alert(a); //check if the value is correct.
    if(a == "value") {-- execute code --}
    
        8
  •  1
  •   ShivarajRH    12 年前
        var arr_select_val=[];
    
        $("select").each(function() { 
            var name=this.name;
                arr_select_val[name]=$('select option:first-child').val();
        });
    
    
    // Process the array object
         $('.orders_status_summary_div').print(arr_select_val);