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
2010-05-16 12:17:55
$('#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
2010-05-16 12:37:52
@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
2010-05-16 12:38:37
No it's not multiple, simple select box.
Beck
2010-05-17 07:41:38
+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
2010-05-16 12:20:28
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
2010-05-16 12:23:00
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
2010-05-16 12:32:09
@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
2010-05-16 12:41:12
.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
2010-08-10 11:54:03
A:
$('select option:selected').attr('selected',false);
// OR
$('select option:selected').attr('selected','');
// OR
$('select').children('[@value='+value+']').attr('selected','');
aSeptik
2010-05-16 12:44:57
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
2010-05-16 12:52:28