Gdubz
Gdubz

Reputation: 61

JavaScript String Comparison in IE8

I'm trying to compare two strings and for some reason, I'm getting "false" as the result.

I've broken down the code to it's most simple function:

<script type="text/javascript">
function selectCat(cat) {
    var catName = cat.firstChild.nodeValue;
    alert(catName);
    if(catName.toString() == "Acronyms") {
        alert("True");
    } else {
        alert("False");
    }
}
</script>
</head>

<body>
<ul>
<li onclick="selectCat(this)">Acronyms</li>
</ul>
</body>

This works just fine in Dreamweaver's Live View, as well as in IE8 (when I press F12 to preview). However, when I upload this page to my company's web content manager (IBM WebSphere Portal), it no longer works.

I don't know what is different between the environments, but it's pretty frustrating. Anyone have any ideas why it might not be treating the category name as a String?

Upvotes: 0

Views: 3135

Answers (2)

imhere
imhere

Reputation: 5025

If IE is including an extra space at the end of nodeValue try -

var catName; 
catName = (catName.toString()).trim();

and then compare it with "Acronyms".

Upvotes: 1

Ryan Erickson
Ryan Erickson

Reputation: 731

For some reason IE is including an extra space at the end of the nodeValue ie what you are actually getting is "Acronyms ".

Edit: To remove the trailing space you can add

if(catName.charAt(catName.length-1) == " "){
    catName = catName.substr(0,catName.length-1);
}

Upvotes: 2

Related Questions