I am new to jquery and ajax. I am trying to set a selected option in my dropdown using my ajax code below:
$.ajax({
        type: "POST",
        url: "sample.php",
        cache: "false",
        dataType: "json",
        success: function(data) {
          //data.month = 03
          $('#birth_month option[value="data.month"]').prop('selected', true);
        }
  });
This is my select html code:
<select id="birth_month" name="birth_month">
<option value="" disabled selected>Month</option>
<option value="01">January</option>
<option value="02">February</option>
<option value="03">March</option>
<option value="04">April</option>
<option value="05">May</option>
<option value="06">June</option>
<option value="07">July</option>
<option value="08">August</option>
<option value="09">September</option>
<option value="10">October</option>
<option value="11">November</option>
<option value="12">December</option>
</select>
And for some reason, it doesn't work. What am I doing wrong?
Thank you in advance for the suggestions.
You have forgotten to concatenate the real value:
$('#birth_month option[value="'+data.month+'"]').prop('selected', true);
This should to the trick but you can use an easier instruction:
$("#birth_month").val(data.month)
                        As date_month is a variable you need to create valid selector using string concatenation
Use .val(), to set value
$('#birth_month').val(data.month);
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With