Search code examples
javascriptinnerhtml

innerHTML return NaN with text


I got a problem, I try to return a value with innerHTML but I got a NaN. I know my variable is not a number but why he keep telling me that ?

function checkWord(id, nameOutput){
    var pattern = new RegExp("\\b(hello|world)\\b", "i");
    var fieldValue = document.getElementById(id).value;
    var result = fieldValue.search(pattern);
    if (result != -1){
        document.getElementById(nameOutput).style.color = "green";
        document.getElementById(nameOutput).innerHTML = +fieldValue+ " is correct";
    }
    else{
        document.getElementById(nameOutput).style.color = "red";
        document.getElementById(nameOutput).innerHTML = +fieldValue+ " is incorrect";
    }
    if(fieldValue == null || fieldValue == ""){
        document.getElementById(nameOutput).style.color = "orange";
        document.getElementById(nameOutput).innerHTML = "Empty field";
    }     
} 

I got always NaN is incorrect or NaN is correct why i can't get the value print ?

If i wrote like this :

document.getElementById(nameOutput).innerHTML ="" +fieldValue+ " is correct";
document.getElementById(nameOutput).innerHTML ="" +fieldValue+ " is incorrect";

Everything works well !! but why i need to write this "" in the innerHTML

Did I do something wrong ?


Solution

  • Change

    document.getElementById(nameOutput).innerHTML = +fieldValue+ " is correct";
    

    to

    document.getElementById(nameOutput).innerHTML = fieldValue + " is correct";
    

    because = +fieldValue is otherwise missing something to add/concatenate to fieldValue. So, instead a cast is made to a number which results in an undefined number, or NaN.

    When you tried

    document.getElementById(nameOutput).innerHTML ="" +fieldValue+ " is correct"; 
    

    you supplied something to concatenate to fieldValue, namely an empty string, so no number conversion was performed on fieldValue.