April 18, 2012

set default value other than options value using jquery

Question by Both FM

<select id="itemDepartment">

  <option value="1">Computer Accessories</option>
  <option value="2">Laptop</option>

</select>

the following attribute set the default value in drop down list

selected="selected"

but I want to select the default value other than options value i.e Please Select Department , when I click on the drop down list then Please Select Department text disappear and options value appear ( as default behavior)

Answer by gdoron

<select id="itemDepartment">
    <option class="placeHolder" value=""> Please Select Department </option>  
    <option value="1">Computer Accessories</option>
    <option value="2">Laptop</option>
</select>​​​​​

$('#itemDepartment').focus(function() {
    $(this).find(".placeHolder").hide();
}).blur(function() {
    $(this).find(".placeHolder").show();
});​

Live DEMO

Answer by Starx

Just add a dummy value with the text you want.

<select id="itemDepartment">
  <option value="" selected="selected">[Please Select Department ]</option>
  <option value="1">Computer Accessories</option>
  <option value="2">Laptop</option>    
</select>

Author: Nabin Nepal (Starx)

Hello, I am Nabin Nepal and you can call me Starx. This is my blog where write about my life and my involvements. I am a Software Developer, A Cyclist and a Realist. I hope you will find my blog interesting. Follow me on Google+

...

Please fill the form - I will response as fast as I can!