如何在ajax响应中检查选项?

时间:2022-05-25 07:18:08

I have an array with checked options values.

我有一个带有检查选项值的数组。

I need to mark checked on my select options form using checkeds array returned from ajax.

我需要使用从ajax返回的checkeds数组在我的select选项表单上标记已选中。

var options = data.options;
var checkeds = data.checkeds;

$.each(options, function(i, item){
    $('#ajax_locals').append($('<option>', {
        value: i,
        text : item,
    }));
});

2 个解决方案

#1


1  

You can use

您可以使用

$('#ajax_locals').append('<option value='+ i +' checked='+ checkeds[i] +'>'+ item +'</option>'

#2


1  

Here is an example: I also added selected in addition to checked. Is this what you are trying to achieve?

这里有一个例子:除了选中之外,我还添加了selected。这就是你想要达到的目标吗?

The only thing I have added is

我唯一补充的是

checkeds[i]

This will take the variable i from the loop and get the corresponding array index from checkeds

这将从循环中获取变量i,并从checkeds中获取相应的数组索引

var options = {
  0: "one",
  1: "two",
  2: "three"
};
var checkeds = {
  0: false,
  1: true,
  2: false
};

$.each(options, function(i, item){
    $('#ajax_locals').append($('<option>', {
        value: i,
        text : item,
        checked: checkeds[i],
        selected: checkeds[i] //Is this what you tried to achieve?
    }));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
  <select id="ajax_locals"></select>
</form>

#1


1  

You can use

您可以使用

$('#ajax_locals').append('<option value='+ i +' checked='+ checkeds[i] +'>'+ item +'</option>'

#2


1  

Here is an example: I also added selected in addition to checked. Is this what you are trying to achieve?

这里有一个例子:除了选中之外,我还添加了selected。这就是你想要达到的目标吗?

The only thing I have added is

我唯一补充的是

checkeds[i]

This will take the variable i from the loop and get the corresponding array index from checkeds

这将从循环中获取变量i,并从checkeds中获取相应的数组索引

var options = {
  0: "one",
  1: "two",
  2: "three"
};
var checkeds = {
  0: false,
  1: true,
  2: false
};

$.each(options, function(i, item){
    $('#ajax_locals').append($('<option>', {
        value: i,
        text : item,
        checked: checkeds[i],
        selected: checkeds[i] //Is this what you tried to achieve?
    }));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
  <select id="ajax_locals"></select>
</form>