Reputation: 3933
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
Reputation: 69915
You can use attribute selector.
$("#three").click(function(){
$(".sel").find('[id=3]').attr('selected', 'selected');
});
Working demo
Upvotes: 2
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
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
Reputation: 140234
$("#three").click(function(){
$(".sel").prop( "selectedIndex", 2 );
})
Upvotes: 1