views:

25

answers:

2

Hello, 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.

+1  A: 

Maybe because you're looking for html within plain text. Try using html instead of text:

var text = jQuery('#div').html();
if (text.indexOf(responseText) == -1) {
   ...
karim79
This works thank you.
netefficacy
A: 

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)
Josh Stodola
This works thank you.
netefficacy