Aditya Singh Aditya Singh - 6 months ago 31
jQuery Question

Cannot read property 'push' of undefined

I am trying to push

data
attribute value into array parameter but it throws the above error on the line parameter[parent].push(parent);

var parameter = {};

var currentTabSelected = "";
var parent = "";

$("#categories").on("click", ":checkbox", function () {
if($(this).is(":checked")) {
parent = $(this).data("parent");
console.log(parent)

if (!(currentTabSelected in parameter)) {
parameter[currentTabSelected] = []
}

var found = $.inArray($(this).val(), parameter[currentTabSelected]) > -1;

if (!(found)) {
parameter[currentTabSelected].push($(this).val());
parameter[parent].push(parent);
console.log(parameter)
}
} else {
var index = parameter[currentTabSelected].indexOf($(this).val());
var parent_index = parameter[parent].indexOf(parent)

if (index > -1) {
parameter[currentTabSelected].splice(index, 1);
parameter[parent].splice(parent_index , 1);
}
}
})


what can i do to overcome the above problem?

p2. p2.
Answer

If parameter is an object you should create keys before using them . You are trying to access the key which is not present in the parameter.

for example , make sure your object contains currentTabSelected and parent

parameter[currentTabSelected] = []
parameter[parent] = []

After initializing currentTabSelected and parent you can perform operation on parameter[currentTabSelected] , parameter[parent] .

Comments