Posted By

halk on 10/16/12


Tagged

select dropdown default Value


Versions (?)

Who likes this?

1 person have marked this snippet as a favorite

BrockSamsom


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


 / Published in: 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"

  1. $(function(){
  2. $('select[value]').each(function(){
  3. $(this).val(this.getAttribute("value"));
  4. });
  5. });
  6.  
  7. //The Markup Looks Like This
  8. <select name="category" id="category" value="PHP"> //NOTICE value attribute!!!
  9. <option value="ARTICLE">ARTICLE</option>
  10. <option value="PHP">PHP</option> //THIS IS THE DEFAULT OPTION
  11. <option value="MySql">MYSQL</option>
  12. <option value="jQuery">jQuery</option>
  13. <option value="CSS(3)">CSS(3)</option>
  14. </select>

Report this snippet  

You need to login to post a comment.