0

Imt rying to loop over some JSON data that is returned and if the value returned is each to an html element attr add "checked" to the checkbox however this keep throwing an error.

$('.varUserSettingTable tr').each(function(index, el) {
    var $this = $(this);
    $.each(curdata.VarUserDetails.VARS, function(index, value) {
        if (curdata.VarUserDetails.VARS[index] !== null) {
            if ($this.find('.SettingCheckbox').attr('name') === curdata.VarUserDetails.VARS[index].userID) {
                $this.find('.SettingCheckbox').prop('checked', true);
            }
        }
    });
});

Its throwing the error "Uncaught TypeError: Cannot read property 'userID' of undefined"

on the if statmenet thats making sure .userID !== null

VarUserDetails: Object
VARS:Array[1024]
    [0 … 99]
        0:null
        1:null
        2:Object
            userChecked:1
            userID:"2"
            __proto__:Object
        3:Object
            userChecked:1
            userID:"3"
            __proto__:Object
        ...
        ...
3
  • 1
    Why are you reading curdata.VarUserDetails.VARS[index] from within the iterator callback? You can simply use value instead. Commented May 3, 2017 at 16:23
  • 1
    I could be wrong but it looks like you have an array between 0:null and VARS. So perhaps value[index][index] !== null) ? Commented May 3, 2017 at 16:23
  • 1
    Also, checking value !== null will not catch undefined. Commented May 3, 2017 at 16:25

1 Answer 1

1

value itself is the item of the array. Trying use value instead of curdata.VarUserDetails.Vars[index]

$('.varUserSettingTable tr').each(function(index, el) {
var $this = $(this);
$.each(curdata.VarUserDetails.VARS, function(index, value) {
    if (value  !== null) {
        if ($this.find('.SettingCheckbox').attr('name') === value.userID) {
            $this.find('.SettingCheckbox').prop('checked', true);
        }
    }
});
Sign up to request clarification or add additional context in comments.

1 Comment

perfect! and more efficient thank you, will award the question after the 5 minute timer

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.