如何使用JSON数据设置选择选项?

时间:2022-12-10 07:08:15

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

我有一系列选择框,有一个像这样的唯一ID。

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

I have a JSON in the format

我有格式的JSON

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

I am using the following Javascript to set the selected value

我使用以下Javascript来设置所选值

   $.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?

这不是选择“是”的值。我怎样才能做到这一点?

2 个解决方案

#1


1  

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

您只需使用.val()来使用对象中的值设置所选选项:

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>

#2


1  

Well, you don't really need jQuery here.

好吧,你真的不需要jQuery。

var select = document.getElementById(SelectObj.id);
select.value = SelectObj.value;

#1


1  

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

您只需使用.val()来使用对象中的值设置所选选项:

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>

#2


1  

Well, you don't really need jQuery here.

好吧,你真的不需要jQuery。

var select = document.getElementById(SelectObj.id);
select.value = SelectObj.value;