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?

closed as off-topic by Samuel De Rycke, Sergej Utko, user248, eyescream, Peter Knolle Jan 15 '14 at 11:25

This question appears to be off-topic. The users who voted to close gave this specific reason:

  • "Programming questions not specific to Salesforce are off-topic here, but can be asked on Stack Overflow." – Samuel De Rycke, Sergej Utko, Gaurav Kheterpal, eyescream, Peter Knolle
If this question can be reworded to fit the rules in the help center, please edit the 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

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