jqueryindexofresponsetext

jQuery Ajax How Do I Pass responseText as variable to indexOf?


I am trying to append a p element from the responseText of an Ajax request.

Before appending, I would like to see if the responseText already exists in the parent div element text, and not add it if that is the case. The problem is I cannot get indexOf(responseText) to work using the variable responseText. My code works when I pass a string literal to indexOf.

Here is my code:

jQuery('#addButton').live('click', function () {

    new Ajax('<url>', {
        method: 'get',
        dataType: 'html',
        onSuccess: function (responseText) {
            var text = jQuery('#div').text();

            if (text.indexOf(responseText) == -1) {
                //always true using responseText; 
                //string literal works though
                jQuery('#div').append(responseText);
            }
        }
    }).request();

})

Thanks in advance for any suggestions.


Solution

  • Wrap the response with jQuery and try the comparison with the text() representation of it...

    var resp = $(responseText);
    var div = $("#div");
    
    if(div.text().indexOf(resp.text()) == -1)
      resp.appendTo(div)