Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set a selected option using ajax?

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.

like image 314
newbie Avatar asked Dec 19 '22 12:12

newbie


2 Answers

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)
like image 133
Patrick Portal Avatar answered Dec 28 '22 17:12

Patrick Portal


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);
like image 39
Satpal Avatar answered Dec 28 '22 17:12

Satpal