Set Default Value for Select Lists Using value attribute with jQuery

For some reason setting a default value for select elements does not work. This one line of jquery solves that problem. Assign a value (value=”something”) to the select tag that is to be the default value. With jquery get all select elements with a (value) attribute set. For some reason I couldnt get the value of (value) with jquery, it would only return the first item in the list and not the value of the attribute(value). Oldschool Javascript managed to return it though. The result is that when the document becomes ready jquery finds all select boxes and changes their value to the value stored in the attribute(value) of the select tag. This means that you can set default values for select elements in the same way you set them for other elements – by assigning them a (value) – value=”whatever”

//The Markup Looks Like This
<select name="category" id="category" value="PHP"> //NOTICE value attribute!!!
<option value="ARTICLE">ARTICLE</option>
<option value="PHP">PHP</option> //THIS IS THE DEFAULT OPTION
<option value="MySql">MYSQL</option>
<option value="jQuery">jQuery</option>
<option value="CSS(3)">CSS(3)</option>

Leave a Reply