Jeroen Bal
Jeroen Bal

Reputation: 33

How to compare strings in jQuery

In this code I am trying to compare two strings with jQuery. The current content of a div and the new content, loaded from a (currently) static page.

But it doesn't work, when the loaded content is the same as the current content, it still loads the new content...

When I view the content vars, they really are equal (I used the JS alert).

$(document).ready(function () {
    var refreshId = setInterval(function () {
        $.get("ajaxGetEvents.aspx", function (data) {
            if ($('#events').html() != data) {
                $('#events').fadeOut('slow', function () {
                    $(this).load('ajaxGetEvents.aspx').fadeIn('slow');
                });
            } else {
                alert("item is equal");
            }
        });
    }, 5000);
});

Upvotes: 3

Views: 56420

Answers (4)

Cyclonecode
Cyclonecode

Reputation: 30131

If your ajax request return a normal text string (not html formated), I think you should use text() instead of html().

$(document).ready(function () {
  var refreshId = setInterval(function () {
  $.get("ajaxGetEvents.aspx", function (data) {
    if ($('#events').text() != data) {
      $('#events').fadeOut('slow', function () {
        $(this).load('ajaxGetEvents.aspx').fadeIn('slow');
      });
     } else {
       alert("item is equal");
     }
   });
  }, 5000);
});

Upvotes: 0

Augustus Kling
Augustus Kling

Reputation: 3333

Are you sure the whitespaces are identical? Let's suppose data is <span >test</span>:

var data = "<span >test</span>";
// Temporarily place your data in a DOMElement to trigger parsing and re-serialization
alert(data===jQuery('<div>').append(test).html());

As you will see, the code above results in false. The reason is a space after the word span. Building a DOM tree removes such whitespaces and calling html does not have a way to restore them.

Note that this answer is just a guess. Please post your HTML to get more useful/targeted answers.

Upvotes: 0

Abe Miessler
Abe Miessler

Reputation: 85126

I suspect you are not getting the values you expect for $('#events').html() and data.

Can you use firebug or developer tools to place a breakpoint at your if statement and inspect the values?

Alternatively you could just throw in a couple of alerts to see what these contain... Example:

alert($('#events').html());
alert(data);
if ($('#events').html() != data) {

That said, if you are not familiar with using firebug or developer tools, now might be a good time to start using them. They will save you a lot of headaches in the future and they are infinitely better than alerts when it comes to debugging.

Upvotes: 0

Manuel van Rijn
Manuel van Rijn

Reputation: 10315

maybe it's beter to compare the .text() instead of the (maybe generated) html

so you have

$("#events").text() == $(data).text()

Upvotes: 3

Related Questions