Reputation: 35
I am trying to update a SELECT dropdown with a new value that is coming back from an Ajax call. I can see that the SELECTed option is changing to "selected", but the form field display is never updated. In the code below, at the end, the option is updated correctly to Selected, but the display still shows "Advanced" not "Open". Any help would be appreciated.
Before the Ajax call
<form action="" id="RankingForm" name="RankingForm" method="post">
<td style="color: white;">
<select name="Ranking">
<option value="4" >Open</option>
<option value="3" selected>Advanced</option
<option value="2" >Intermediate</option>
<option value="1" >Beginner</option>
</select>
</td>
</form>
The Jquery code
success: function (data) {
$('.Ranking option[value=data.RankingID]').attr("selected", "selected");
},
The JSon response
{ClimberID: "1", Message: "Ranking updated successfully.", RankingID: "4", Success: "1"}
Post JQuery function
<form action="" id="RankingForm" name="RankingForm" method="post">
<td style="color: white;">
<select name="Ranking">
<option value="4" selected>Open</option>
<option value="3" >Advanced</option>
<option value="2" >Intermediate</option>
<option value="1" >Beginner</option>
</select>
</td>
</form>
Upvotes: 0
Views: 394
Reputation: 147216
You have a couple of issues. Firstly, your select
doesn't have a class of Ranking
, that is its name. So to access it, you should use $('select[name=Ranking]')
, not $('.Ranking)
. Secondly, to set the value of a select
using jQuery, we just use $.val()
rather than trying to set the selected
attributes of the options. This demo shows the option changing after 1 second...
const update_ranking = function(data) {
$('select[name=Ranking]').val(data.RankingID);
};
const data = {
ClimberID: "1",
Message: "Ranking updated successfully.",
RankingID: "4",
Success: "1"
};
setTimeout(update_ranking, 1000, data);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form action="" id="RankingForm" name="RankingForm" method="post">
<td style="color: white;">
<select name="Ranking">
<option value="4">Open</option>
<option value="3" selected>Advanced</option>
<option value="2">Intermediate</option>
<option value="1">Beginner</option>
</select>
</td>
</form>
Upvotes: 1