设置选择元素的选定值

时间:2012-01-10 20:32:20

标签: javascript jquery html

我有两个选择列表:

<select id="one" class="sel">
    <option id="1">1</option>
    <option id="2">2</option>
    <option id="3">3</option>
</select>

<select id="two" class="sel">
    <option id="1">1</option>
    <option id="2">2</option>
    <option id="3">3</option>
</select>

和span:

<span id="three">set three</span>

我想点击这个范围,应该在两个列表中选择(id一和二)选项id = 3。 我该怎么做?

$("#three").click(function(){
    $(".sel") ... ????
})

LIVE: http://jsfiddle.net/rUbGx/

顺便说一句。我想在选项中使用ID的示例,而不是值。感谢。

5 个答案:

答案 0 :(得分:3)

id s中将value更改为option,然后:

$("#three").click(function(){
    $(".sel").val(3);
});

另请参阅更新的example

答案 1 :(得分:2)

您可以使用属性选择器。

$("#three").click(function(){
    $(".sel").find('[id=3]').attr('selected', 'selected');
});

工作demo

答案 2 :(得分:2)

使用val功能。

$("#three").click(function(){
    $(".sel").val("3");
})

每个认为你需要在option上设置价值的人:你没有。看看jQuery核心:

option: {
            get: function( elem ) {
                var val = elem.attributes.value;
                return !val || val.specified ? elem.value : elem.text;
            }
        },

如果没有值属性,则使用option的文本。因此,调用val(3)将搜索文本值为“3”的选项,并选择适当的元素。 ID不是唯一的无关紧要。

小提琴:http://jsfiddle.net/Qrbs2/

答案 3 :(得分:1)

$("#three").click(function(){
    $(".sel").prop( "selectedIndex", 2 );
})

http://jsfiddle.net/rUbGx/3/

答案 4 :(得分:1)

只是为了好玩而做了这个..在这里检查我的DEMO

var txt2Num = ['zero', 'one', 'two', 'three', 'four', 'five','six', 'seven', 'eight', 'nine'];
$("#three").click(function(){
    var textNum = $.trim($(this).text()).replace('set ', '');
    var selectedIndex = $.inArray(textNum, txt2Num);   

    $(".sel").each (function (index) {       
        this.selectedIndex = selectedIndex - 1;
    });
});