Return to Snippet

Revision: 60013
at October 16, 2012 01:33 by halk


Initial Code
$(function(){
    $('select[value]').each(function(){
        $(this).val(this.getAttribute("value"));
    });
});

//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>
</select>

Initial URL


Initial Description
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"

Initial Title
Set Default Value for Select (dropdown) Lists Using value attribute

Initial Tags
dropdown

Initial Language
jQuery