[英]auto check checkboxes for matching result in ajax call
I'm trying to make it so that when my ajax call is returned with an object/array, I can match up the results to checkboxes so that if there is a match I auto check the boxes我正在努力做到这一点,以便当我的 ajax 调用与对象/数组一起返回时,我可以将结果与复选框匹配,以便如果匹配,我会自动选中复选框
Here are my checkboxes这是我的复选框
<input type="checkbox" name='Magazine' data-md-icheck />
<input type="checkbox" name='Website' data-md-icheck />
<input type="checkbox" name='Advertisement' data-md-icheck />
Now my ajax call is successful现在我的 ajax 调用成功
I get back:我回来了:
0: {}
type: "Magazine"
1: {}
type: "Website"
so in my ajax success, what I would like to do is take any result in that object, whether just one or all 3, and if the type matches the 'name' of the checkbox I want to check that box.所以在我的 ajax 成功中,我想做的是在 object 中获取任何结果,无论是一个还是全部 3,如果类型与复选框的“名称”匹配,我想选中该框。
Here is my function that makes the successful ajax call.这是我的 function 调用成功的 ajax。 I just can't figure out a way to loop the return that I get so that I can match up any result that comes through
我只是想不出一种方法来循环我得到的回报,以便我可以匹配任何通过的结果
function getDetails(ID) {
console.log(ID);
$.ajax({
url: "/details",
data: {ID:ID},
_token: "{{ csrf_token() }}",
type: "POST",
success: function (data) {
},
});
};
So in this case, how would I modify my ajax success to check the magazine and website boxes?那么在这种情况下,我将如何修改我的 ajax 成功以检查杂志和网站框?
Here is a pure JS and simple solution to this:-这是一个纯JS和简单的解决方案:-
// Assuming you get the response as an array of objects, which has a key as type
success: function (data) {
data.forEach(obj => {
let ele = document.getElementsByName(obj.type)[0];
if(ele) {
ele.checked = true;
}
});
}
This is how I would tackle it:这就是我将如何解决它:
function getDetails(ID) {
console.log(ID);
$.ajax({
url: "/details",
data: {ID:ID},
_token: "{{ csrf_token() }}",
type: "POST",
success: function (data) {
for(var i=0;i<data.length;i++){
var item = data[i].type;
var checkbox = $('input[name="'+item+'"]);
if (checkbox.length){
checkbox.prop('checked', true);
}
}
},
});
};
Assume the result is pure text exactly the same as you provided (ES6+)假设结果是与您提供的完全相同的纯文本(ES6+)
let a = 'result...' ['Magazine', 'Website', 'Advertisement'].filter(item => a.indexOf(item).= -1).forEach(item => { let inputs = document.getElementsByName(item) if (inputs.length > 0) inputs[0].checked = true })
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.