Ajax复选框调用

I am trying to get an ajax request to tick a box if a certain value is returned.

Basically I have the following code:

     for(var id in data) {        
              $(id).val( data[id] );
              if($(newsletter).val( data[newsletter])) {

                       $('#newsletter').prop('checked', true);

              }
     }

Now I've tried the following code and no dice.

for(var id in data) {        
              $(id).val( data[id] );
              if($(newsletter).val( data[newsletter] == 1)) {

                       $('#newsletter').prop('checked', true);

              }
     }

This will tick the checkbox for any result returned however if the value is 1 I would like it to then check the box if another value is returned I'd like it to not be ticked.

If I'm doing something wrong please let me know, as I am new to both jQuery and stackoverflow.

Maybe this might work : if($(newsletter).val() == 1... or: if(data[newsletter] == 1)...

it seems you have there is a missing assignment: maybe you mean var newsletter = $(id).val( data[id] ); I can't figure it out. Please explain, how newsletter is declared.

I'm going to assume that data is the object returned via AJAX, and that data[newsletter] is a valid way of accessing some property of that object, which you want to check the value of.

If so, then the following should work:

if (data[newsletter] === 1) {
    $('#newsletter').prop('checked', true);
}

Also, the reason that the code if($(newsletter).val( data[newsletter] == 1)) { is setting it checked for any value is because what you are actually testing with the if is the return value from the .val() call, which is a jQuery object, which is always going to evaluate as true, even if there are no elements that match the selector.

Protip: If you want to check if a jQuery selector matched any elements, test the .length property instead.

e.g.

if ($('.my_selector:eq(0)').length) {
     alert('Found one!');
}