Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 ?

like image 850
Pierre Avatar asked Apr 15 '26 09:04

Pierre


2 Answers

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.

like image 169
Drakes Avatar answered Apr 16 '26 21:04

Drakes


This is happening because you make a conversion (+fieldValue) to number. When you add "" in front of you make a conversion to string (""+fieldValue). You can read more about JavaScript type conversion here.

like image 35
adricadar Avatar answered Apr 16 '26 23:04

adricadar