is it possible to set a default value of a <select> element without using the selected option on the element?
I am looking for a solution that would work from the <select> element itself, something like:
<select name="country" style="width:210px;" [defaultvalue="option1"]>
....options....
</select>
(enclosed in the [ ] is for illustration of what I am looking for)
Is it possible to do this HTML only? Or better set it with jQuery? Other ideas?
2 Answers 2
If you want to use jQuery and set the default value on the client you could use the .val() function:
$('select[name="country"]').val('fr-FR');
Assuming you have an <option> element with value="fr-FR" this will effectively preselct this option in the dropdown.
Obviously if you are using a server side language to generate your markup it would be better to add the selected="selected" attribute on the corresponding option directly on the server rather than on some client scripting. This would be semantically more correct. This way you won't even be relying on some client scripting and clients that might have disabled javascript and so on. Your server would have accomplished his job by generating semantiaclly correct markup and now it will be the responsibility of the user agent to display this markup.
2 Comments
.val() function.It can't be done without using the selected attribute or javascript, however, here's a little example of how to do it with jquery :
<select name="country" style="width:210px;" data-default="egypt">
....options....
</select>
var sel = $('select[name="country"]'),
def = sel.data('default');
if(def) sel.val(def);
<option>, I need to do it from the<select>$('select[name="country"]').val('value')