I am having javascript problem in my VF page so I am posting this question here.

Here is my code

 <input id="xyz" value="&nbsp;"/>
    alert( document.getElementById('xyz').value);
    var x = document.getElementById('xyz').value;
    if(  x == '&nbsp;' )

The input field xyz is having the value as   I am checking the value in javascript but the if condition never evaluates to true. What could be the problem?

| improve this question | | | | |

The problem is in the fact that you are comparing two string objects, which although containing identical value do not necessarily pose two instances of identical object.

E.g. contraty to usual expectations, the following JS code will result with false

var a = "some string";
var b = "some string";
alert(a == b);

What you should do is wrap each side of the comparison in an String.valueOf(), which will return the primitive value of the String object:

String.valueOf(document.getElementById('xyz').value) == String.valueOf("&nbsp;")

For more info on string comparison in JS and good practices in JS comparison overall, visit this link: https://stackoverflow.com/questions/3586775/javascript-string-equality-whats-the-correct-way

| improve this answer | | | | |

Not the answer you're looking for? Browse other questions tagged or ask your own question.