user813813 user813813 - 2 months ago 8
Javascript Question

How do I set select options using JSON data?

I have an array of select boxes, with a unique id like this.

<select class="taskcompleted" id="c392018">
<option value="No">No</option>
<option value="Yes">Yes</option>
</select>


I have a JSON in the format

{"id":"c392018","value":"Yes"}


I am using the following Javascript to set the selected value

$.getJSON('getstatus.php') //place correct script URL
.done(function(response) {
$.each(response, function(key) {
var SelectObj = response[key];
console.log(SelectObj['value']);
jQuery('#' + SelectObj['id']).val(SelectObj['value']).attr('selected', true);
});
});


This is not selecting the value of "Yes". How can I do this?

Answer

You simply need to use .val() to set the selected option using the value from your object:

So where you have:

jQuery('#' + SelectObj['id']).val(SelectObj['value']).attr('selected', true);

Should be:

jQuery('#' + SelectObj['id']).val(SelectObj['value']);

See the snippet example below:

Also if you really want the selected property on the item, you should use:

.prop("selected", "selected");

var SelectObj = {"id":"c392018","value":"Yes"};
jQuery('#' + SelectObj['id']).val(SelectObj['value']).prop('selected','selected');
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select class="taskcompleted" id="c392018">
   <option value="No">No</option>
   <option value="Yes">Yes</option>
</select>

Comments