April 17, 2012

select value of dropdownlist item jquery

Question by Both FM


<select id="selectDepartment">
  <option value="1">120</option>
  <option value="2">20</option>
  <option value="3">140</option>
  <option value="4">4120</option>
  <option value="5">560</option>
  <option value="6">451</option>
  <option value="7">310</option>
  <option value="8">656</option>
  <option value="9">444</option>
  <option value="10">555</option>
  <option value="11">2560</option>
  <option value="12">450</option>


$("#selectDepartment").change( function() {

alert($("select option:selected").val()); 


the above function always shows value 1 on alert, when I select any one of the options

Answer by Brad Christie

Your method of finding the selection option is vague. You’re saying “Grab all <select>s”. You then go on to grab the :selected option from each of them (of all <select>s on the page). Continued, .val() takes the first value off the top.

Simply put, you’re always fetching the selected value of the first <select> found on the page. Assuming #selectDepartment isn’t the first <select>, your value will never change.

Try to keep the scope to within the current <Select> using this:

  var selopt = $('option:selected',this);

Note that I specify the scope to within the <select> that triggered the .change(). Also note this really isn’t necessary as val() works just as easily:

var selopt = $(this).val();

Let jQuery do the heavy lifting. You really only need option:selected if you want control over styling that specific element, or you’re working with a multi-select and want more control.

Answer by Starx

You can do something like this:

$("#selectDepartment").change( function() {

     var selected = $(this).find(":selected");


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!