I am trying to get the substring from a variable when the content length is longer than 120 chars.
$.ajax({
url: url,
dataType: 'json',
async: false,
success: function(data){
$.each(data, function(i, item) {
var name = item.name;
var itemId = item.itemId;
if(name.length >= 120) {
selectHTML += '<option value=' + itemId + '>' + name.substr(0, 120) + '</option>';
} else {
selectHTML += '<option value=' + itemId + '>' + name + '</option>';
}
});
}
});
But as a result, I always get this:
name is undefined
When I do it without substring(), it works without problems. Any suggestions?
Edit:
Error is thrown on this line:
if(name.length >= 120) {
Try changing
if (name.length >= 120)toif (name && name.length >= 120)