sam sam - 5 months ago 29
Javascript Question

jquery dynamic change of value to select box not working

I'm a kind of stuck as everything else is working fine for me but when I try to get the value of my select dropdown from jquery, it still shows the selected value (value set prior to the new value).
Have gone through jquery dropdown change and a couple more but they didn't help much, probably I'm not accessing the right property.

<select name="RP_6199" class="form-control" id="RP_6199">
<option value="-1">Unknown</option>
<option value="1">A</option>
<option selected="selected" value="2">B</option><!--currently selected value-->
<option value="3">C</option>
<option value="4">D</option>
<option value="5">E</option>
</select>


The code I'm doing is

$("select[name=rp_" + individual.type + "]").each(function () {
individual.rpId = $("select[name=rp_" + individual.type + "] option:selected").val();
});


please ignore any naming errors as i have just replaced the original names by some other names for confidentiality.
Somehow, the selected value I'm getting here is still showing the old option, though I have changed the option.

Answer

$('#RP_6199').change(function(){
alert($('option:selected',this).val())

}).change();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select name="RP_6199" class="form-control" id="RP_6199">
    <option value="-1">Unknown</option>
    <option value="1">A</option>
    <option selected='selected' value="2">B</option><!--currently selected value-->
    <option value="3">C</option>
    <option value="4">D</option>
    <option value="5">E</option>
</select>

  1. Use .change()
  2. Call change event manually to show the value of selected option on load
  3. Wrap the code in document ready