Rafe
Rafe

Reputation: 3066

Why doesn't IE7 think these two strings are equal?

I have an event handler that will remove an element from a list of the corresponding checkbox is unchecked. In the handler for the click event for the checkbox, first I copy the value of the label for that checkbox:

var label = $(this).next().html();

Then, I iterate over the list items and compare each of them to that label:

  $("#sortable li").each(function() {
    if ($(this).html() === label) {
      $(this).remove();
    }
  });

In Internet Explorer 8 and in Firefox, this works exactly as I'd expect. In Internet Explorer 7, it does not. The condition in the "if" statement is never true. What am I missing here?

By request, the strings being compared are, "Charge" and "Charge" in one case.

Upvotes: 1

Views: 670

Answers (4)

Kip
Kip

Reputation: 109503

Not an answer to your direct question, but here's another method that uses jQuery's data method to set and read a flag directly on the element:

$(this).next().data("toRemove", true);

//...

$("#sortable li").each(function() {
  if ($(this).data("toRemove")) {
    $(this).remove();
  }
});

Of course, if you were manipulating label at any point then this wouldn't be what you want. I just mention this because .data() is a very useful jQuery feature that I haven't heard much about. I didn't even know about it until a week ago.

Upvotes: 0

Rodrigo
Rodrigo

Reputation: 4395

Why don't you use the Script Debugger and see exactly why that comparison is false? Just set a breakpoint in the if and watch the variables.

The IE8 internal script debugger will help you, just switch to compatibility mode to run the script in the IE7 javascript runtime

Upvotes: 2

chaos
chaos

Reputation: 124365

  1. Try alert(label) and alert($(this).html()) to see exactly what's being compared.
  2. I'm not seeing any reason to use strict comparison (===), and you could conceivably benefit from using ordinary comparison (==).
  3. As a method of doing what you're saying you want to do, this all seems pretty crazy. I'd always recommend identifying corresponding DOM elements by something more designed-for-the-purpose than their HTML contents, such as an ID.

Upvotes: 4

Marius
Marius

Reputation: 59009

Have you tried debugging it? Use alert to see what the two values hold, check that the function is actually called in IE7 and check that they have the same type.

Upvotes: 1

Related Questions