I have a snippet of javascript that I’m using to track form engagement. I use $(this) to pass an object to two functions in my script but my next few lines of code aren’t executed because Chrome says “Cannot read property ‘length’ of undefined. Why can’t I use the $(this) reference anymore?
$('select').blur(function () {
var input_category = get_input_category($(this));
var form_identifier = get_form_identifier($(this));
if($(this).attr('name').length) {
// This is where I get the error ^^
var object_identifier = $(this).attr('name');
}
else if($(this).attr('id').length) {
var object_identifier = $(this).attr('id');
}
else if($(this).attr('class').length) {
var object_identifier = $(this).attr('class');
}
else {
var object_identifier = null;
}
});
Edit: The select box doesn’t have a name value attached.
<select type="select">
<option value="volvo">Volvo</option>
<option value="saab">Saab</option>
<option value="mercedes">Mercedes</option>
<option value="audi">Audi</option>
</select>
But isn’t that what my script looks for? If it doesn’t have a name, I want it to move on. How do I check for the attribute without getting an error?
As was seen by Vega, the problem is on the
attr('name')value.Don’t check the length of an object to check it’s defined, because this will raise an error when there is no object on which the length could be taken.
Simply check it’s defined and has a non empty value using the usual js pattern :
instead of
Note that the first test checks also this isn’t
"". So there is absolutely no reason to check both that the object is defined and isn’t"".