Both FM
Both FM

Reputation: 770

select value of dropdownlist item jquery

HTML

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

jQuery

$("#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

Upvotes: 0

Views: 1011

Answers (2)

Starx
Starx

Reputation: 78941

You can do something like this:

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

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

});

Upvotes: 0

Brad Christie
Brad Christie

Reputation: 101594

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:

$('#selectDepartment').change(function(){
  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.

Upvotes: 5

Related Questions