Mark Fondy
Mark Fondy

Reputation: 3933

Set the selected value of a select element

I have two select list:

<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>

and span:

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

i would like click on this span and should in two list select (id one and two) be option id=3 selected. How can i make it?

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

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

btw. i would like example with ID in option, not with value. Thanks.

Upvotes: 0

Views: 235

Answers (5)

ShankarSangoli
ShankarSangoli

Reputation: 69915

You can use attribute selector.

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

Working demo

Upvotes: 2

benesch
benesch

Reputation: 5269

Use the val function.

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

Everyone who thinks you need to set a value on the option: you don't. Look at the jQuery core:

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

If there's no value attribute, the text of option is used instead. Thus, calling val(3) will search for an option with a text value of "3", and select the appropriate element. That the IDs aren't unique is irrelevant.

fiddle: http://jsfiddle.net/Qrbs2/

Upvotes: 2

Selvakumar Arumugam
Selvakumar Arumugam

Reputation: 79850

Just did this one for fun.. Check my DEMO here

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;
    });
});

Upvotes: 1

Esailija
Esailija

Reputation: 140234

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

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

Upvotes: 1

scessor
scessor

Reputation: 16125

Change id to value in options, then:

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

Also see your updated example.

Upvotes: 3

Related Questions