Reputation: 5732
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) {
Upvotes: 0
Views: 3554
Reputation: 318518
The error means that one of the item
s does not contain a name
.
Use console.log(data)
to figure out what you actually receive - nothing is wrong with your JavaScript code.
If you cannot change the server-side code, you could fallback to an empty name:
var name = item.name || '';
Upvotes: 0
Reputation: 122916
Try changing if (name.length >= 120)
to if (name && name.length >= 120)
Upvotes: 2