首页 文章

使用jquery选择下拉选项

提问于
浏览
135

我想知道是否有可能让jQuery在下拉框中选择一个选项,比如说第4项?

<select>
    <option></option>
    <option></option>
    <option></option>
    <option></option>
    <option></option>
</select>

我希望用户单击一个链接,然后让选择框更改其值,就像用户通过单击选项选择它一样 .

13 回答

  • 3

    我会这样做的

    $("#idElement").val('optionValue').trigger('change');
    
  • 7

    如果要选择具有特定值的选项,请使用以下代码:

    $('select>option[value="' + value + '"]').prop('selected', true);
    
  • 11

    我更喜欢nth-child()到eq(),因为它使用基于1的索引而不是基于0的索引,这在我的大脑上稍微容易一些 .

    //selects the 2nd option
    $('select>option:nth-child(2)').attr('selected', true);
    
  • 19

    使用''元素通常我们使用'value'属性 . 它会使设置更容易:

    $('select').val('option-value');
    
  • 2

    试试这个:

    $('#mySelectElement option')[0].selected = true;
    

    问候!

  • 3

    回答id:

    $('#selectBoxId').find('option:eq(0)').attr('selected', true);
    
  • 0
    Try with the below codes. All should work. 
        $('select').val(2);
        $('select').prop('selectedIndex', 1);
        $('select>option[value="5"]').prop('selected', true);
        $('select>option:eq(3)').attr('selected', 'selected');
        $("select option:contains(COMMERCIAL)").attr('selected', true);
    
  • 132

    如果您的选项有值,您可以这样做:

    $('select').val("the-value-of-the-option-you-want-to-select");
    

    'select'将是您的select或类选择器的id . 或者如果只有一个选择,您可以使用示例中的标记 .

  • 162

    怎么样

    $('select>option:eq(3)').attr('selected', true);
    

    例如http://www.jsfiddle.net/gaby/CWvwn/


    对于现代版本的jquery,您应该使用.prop()而不是 .attr()

    $('select>option:eq(3)').prop('selected', true);
    

    例如http://jsfiddle.net/gaby/CWvwn/1763/

  • 43

    解决方案:

    $("#element-id").val('the value of the option');
    
  • 21

    HTML select元素具有selectedIndex属性,可以写入以选择特定选项:

    $('select').prop('selectedIndex', 3); // select 4th option
    

    使用纯JavaScript可以通过以下方式实现:

    // use first select element
    var el = document.getElementsByTagName('select')[0]; 
    // assuming el is not null, select 4th option
    el.selectedIndex = 3;
    
  • 2

    最简单的方法是 val(value) 功能:

    $('select').val(2);
    

    要获得所选值,您不需要参数:

    $('select').val();
    

    另外,如果你有 <option value="valueToSelect">...</option> ,你可以这样做:

    $('select').val("valueToSelect");
    

    DEMO

  • 3
    $('select>option:eq(3)').attr('selected', 'selected');
    

    这里需要注意的一点是,如果你有javascript正在观看select / option的更改事件,你需要添加 .trigger('change') 以便代码成为 .

    $('select>option:eq(3)').attr('selected', 'selected').trigger('change');
    

    因为只调用 .attr('selected', 'selected') 不会触发事件

相关问题