views:

138

answers:

4

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.

+1  A: 

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.

Marius
+4  A: 
  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.
chaos
I have tried debugging with the alert() function of course. The strings are the same (visibly). And of course they're both obtained in exactly the same way (using jQuery's html() method).
Rafe
And as far as the elements go, using a proper selector and the contents is no less robust than using IDs in this case, and it saves me from having to do stupid string parsing tricks.
Rafe
+2  A: 

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

Rodrigo
Running it in the IE8 debugger in IE7 revealed the problem. For some reason IE is adding a space at the end of the string even though it's not in the HTML source and Firefox and IE8 don't add it.
Rafe
I meant IE7 browser mode.
Rafe
A: 

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.

Kip