Reputation: 1655
I use this function to append a title attr to every tr
of my table. The content for the table is coming from an array. That works fine. But I also have a function with adds manually rows to the table. For these rows, I get an exception. Pretty clear, because they are not in the array. But how can I avoid these exceptions? I don't need to add titles to these rows.
it says:
Cannot read property 'dictCanon' of undefined(…)
function postBody() {
// add title to tr
var trs = $table.find('tbody').children();
for (var i = 0; i < trs.length; i++) {
$(trs[i]).mouseover(function(e) {
index = $(e.currentTarget).data('index');
var d = (diagnosis[index].additionalParameters);
console.log('d', d);
dt = $(e.currentTarget).parent().parent().find('thead').find('th')
.eq($(e.currentTarget).data('index')).data();
//console.log(dictCanon);
if (d != undefined || d !== 'null') {
var dictCanon = diagnosis[index].additionalParameters.dictCanon;
var icd = diagnosis[index].additionalParameters.icd;
$(this).attr('title',icd + ' ' + dictCanon);
}
});
};
};
Upvotes: 1
Views: 944
Reputation: 351218
The error "cannot read property 'dictCanon' of undefined" is triggered on this expression:
diagnosis[index].additionalParameters.dictCanon
...which means you have entries in diagnosis
that have no additionalParameters
property. You tried to protect the code against that error, but did it with the wrong boolean operator. Use &&
instead of ||
and don't put null
in quotes. I would also suggest to adapt the condition in your for
loop to make sure you have the necessary entry in diagnosis
:
function postBody() {
// add title to tr
var trs = $table.find('tbody').children();
for (var i = 0; i < trs.length && i < diagnosis.length; i++) {
$(trs[i]).mouseover(function(e) {
var index = $(e.currentTarget).data('index'); // use `var`
var d = diagnosis[index].additionalParameters // parentheses not needed
console.log('d', d);
dt = $(e.currentTarget).parent().parent().find('thead').find('th')
.eq(index).data(); // you have `index`, use it
//console.log(dictCanon);
if (d !== undefined && d !== null) { // <--- changed!
var dictCanon = d.dictCanon; // <-- you have `d`, use it
var icd = d.icd; // <-- idem
$(this).attr('title',icd + ' ' + dictCanon);
}
});
};
};
Note also some other changes I made... see comments in code.
Upvotes: 1