Zamboo
Zamboo

Reputation: 539

Variable affectation or IF statement IE issues

I have this (very) simple code:

var myvar = $('.selected').text();
if (myvar == "foo") { //do some stuff...}

It works in Firefox, not in IE_6. What's the problem?

Of course I alert($('.selected').text()) which gives me the right value.

And I change the code to:

var myvar = "foo";
if (myvar == "foo") { //do some stuff...}

Then it works in IE.

any explanation?

Upvotes: 1

Views: 188

Answers (3)

Pointy
Pointy

Reputation: 414086

It's possible that IE is giving you some whitespace that Firefox isn't (or vice-versa). Try this:

var myvar = $('.selected').text().replace(/^\s*(.*\S)\s*$/, '$1');

and see if that helps.

Upvotes: 0

Spudley
Spudley

Reputation: 168853

Is the code being called on page load? If so, have you wrapped it in a $(document).ready() function?

If not, it might be getting run while the DOM is still being constructed, and since IE is slower at building the DOM than Firefox, IE might not have built the .selected element by the time it runs this code, whereas Firefox could have.

I've seen a number of issues with JQuery that looked like cross-browser issues at first glance, but turned out to be just because of not using $(document).ready().

The white-space suggestions in the other answers also sound plausible, though.

Upvotes: 0

Liv
Liv

Reputation: 6124

you are selecting a set of elements which have class="selected" -- if there is more than one element in the list you might end up with a few spaces before/after the actual "foo" text. Have you verified that is not the case? Try changing to using id=selected if possible -- i.e. $("#selected") which should give you one element only.

Upvotes: 2

Related Questions