Omer Aviv
Omer Aviv

Reputation: 284

Comparing jQuery returned string with another string

I'm trying to compare a jQuery returned string (accessed by msg.d) and another string. This is currently what I have done, but it seems like it's not working and saying it's not equal every time:

setTimeout(ReloadChatMsgs, 1000);
function ReloadChatMsgs() {
    var msgs = document.getElementById("msgs_list");
    $.when($.ajax({
        type: "POST",
        url: 'Login.aspx/ReloadChatMsgs',
        data: '{}',
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function (msg) {
            if (msgs.innerHTML != msg.d.toString())
                msgs.innerHTML = msg.d;
        },
        failure: function (e) {

        }
    })).then(function () { setTimeout(ReloadChatMsgs, 1000); });
}

Upvotes: 0

Views: 85

Answers (2)

Omer Aviv
Omer Aviv

Reputation: 284

I just checked both values of msg.d and msgs.innerHTML and they are a bit different because msgs.innerHTML is already parsed to HTML codes (space for example). I resolved it by saving the last msg.d in a different var and used this to compare.

var last_msgs_set = "";
setTimeout(ReloadChatMsgs, 1000);
function ReloadChatMsgs() {
    var msgs = document.getElementById("msgs_list");
    $.when($.ajax({
        type: "POST",
        url: 'Login.aspx/ReloadChatMsgs',
        data: '{}',
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function (msg) {
            if (last_msgs_set != msg.d) {
                msgs.innerHTML = msg.d;
                last_msgs_set = msg.d;
            }
        },
        failure: function (e) {

        }
    })).then(function () { setTimeout(ReloadChatMsgs, 1000); });
}

Upvotes: 0

Tushar
Tushar

Reputation: 87203

If you want to compare two strings irrespective of case

  1. Trim both the strings
  2. Convert both to lowercase

Code:

if ($.trim(msgs.innerHTML.toLowerCase()) != $.trim(msg.d.toString().toLowerCase()))
    msgs.innerHTML = msg.d

Hope this helps

Upvotes: 1

Related Questions