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
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#selectDepartmentisn’t the first<select>, your value will never change.Try to keep the scope to within the current
<Select>usingthis:Note that I specify the scope to within the
<select>that triggered the.change(). Also note this really isn’t necessary asval()works just as easily:Let jQuery do the heavy lifting. You really only need
option:selectedif you want control over styling that specific element, or you’re working with a multi-select and want more control.