Ricky Ricky - 2 months ago 15
Javascript Question

Why does this length check not work?

I am incorporating a minimum length into my input field.
However on the console it returns:


"Cannot read property Length of Null"


Now i assume this is to do with my required value check, yet if i swap the length (if) into the else part of the loop, it still doesn't work for me.
Could someone please tell me what i am doing wrong here.



function validFirst()
{
checkFirst = document.getElementById('first').value;

if(checkFirst){
checkFirst = "";
checkFirst = null;
document.getElementById('firstError').innerHTML="";
document.getElementById('first').style.backgroundColor="#fff";
if(checkFirst.length < 3){
document.getElementById('firstError').innerHTML="**Response too short.";
document.getElementById('firstError').style.color ="#cc0000";
document.getElementById('first').style.backgroundColor = "#cc0000";
}
} else {
document.getElementById('firstError').innerHTML="**Required Field";
document.getElementById('firstError').style.color ="#cc0000";
document.getElementById('first').style.backgroundColor = "#cc0000";
}
}

<tr>
<td>First Name</td>
<td><input type="text" id="first" onblur="validFirst()"></td>
<td><span id="firstError"></td>
</tr>




Answer
    if(checkFirst){
    checkFirst = "";   // <---- YOU ALSO SET IT TO BLANK
    checkFirst = null; // <---- YOU SET IT TO NULL
    document.getElementById('firstError').innerHTML="";
    document.getElementById('first').style.backgroundColor="#fff";
        if(checkFirst.length < 3){

You set checkFirst to null. Therefore it has no length, thus the error.

As an added bonus, even if you remove checkFirst = null;, you set checkFirst to blank prior to that. Therefore, checkFirst will have zero length and the condition checkFirst.length < 3 will always be satisfied.