tags:

views:

84

answers:

3

Thanks for tip. :)

+1  A: 

If you're talking about a <select> just set the value using .val() like this:

$('#mySelect').val('new value');

This automatically selects the <option> with that value.

Nick Craver
$('#slot').find('option:selected').removeAttr('selected');$('#slot').val('0');Thanks this works for me. Strange, but val() doesn't remove attr selected from previous option.
Beck
@Beck - Is it a `<select multiple>`? Just `.val()` won't remove it...that's for getting the current value, `.val('new value')` changes it, but `.val()` with no params doesn't have any *setting* effect.
Nick Craver
No it's not multiple, simple select box.
Beck
+2  A: 

You want something like

$('#mySelect option:selected').removeAttr('selected');

$('#mySelect option:nth-child(5)').attr('selected','selected');//select the one you want

btw, are you talking about a select list single (e.g. dropdown)?... or a select multiple? - you'll need to adjust accordingly if this is a multi-select.

I updated the nth child selector... when setting the selected attribute as square bracket notation [4] doesn't work in the selector.

scunliffe
This only answers the first half of the question :)
Nick Craver
yeah, hit enter too soon ;-)
scunliffe
That's an incredibly long way to do what `.val()` does, and doesn't even allow you to select by value...which is almost always what you want :)
Nick Craver
I guess it all depends what info you have handy. I've also had a scenario where I have multiple options with the same value, but different labels (e.g. you are picking a person, but under the covers selecting a department) does .val() work on a select if you pass either the value of the value attribute or the option text?
scunliffe
@scunliffe - It doesn't select on text, not anymore anyway, this used to be the case. For that you'd pass a function into `.val()`, or do a selector based on text.
Nick Craver
.val() will not work if you are saving the state of the DOM for later use. Unless you remove the attribute, and add it back, such as scunliffe has done, you will have problems.
Derrick
A: 
$('select option:selected').attr('selected',false);
   // OR 
$('select option:selected').attr('selected','');
   // OR 
$('select').children('[@value='+value+']').attr('selected','');
aSeptik
although setting the attribute to an empty/false value works I think that calling .removeAttr() is a little more clear http://api.jquery.com/removeAttr/
scunliffe