JQuery Ajax How to pass responseText as a variable to indexOf?

I am trying to add a p-element from a responseText of an Ajax request.

Before adding, I would like to see if responseText already exists in the text of the parent div element, and not add it if it is. The problem is that I cannot get indexOf (responseText) to work using the responseText variable. 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.

+3
source share
3 answers

Wrap the answer with jQuery and try comparing with its representation text()...

var resp = $(responseText);
var div = $("#div");

if(div.text().indexOf(resp.text()) == -1)
  resp.appendTo(div)
+1
source

, , html . html text:

var text = jQuery('#div').html();
if (text.indexOf(responseText) == -1) {
   ...
+3

No solutions above worked for me (jQuery 1.11.2).

But I finally found my solution: $(my_variable).selector

It works without problems for me:

var responseText = "word";
var resp = $(responseText).selector;



$("div").each(function() {
  if ($(this).text().indexOf(resp) >= 0) {
    alert("I've found your query: " + resp + " at " + $(this).offset().left + "/" + $(this).offset().top);
  }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div>THis is a test</div>
<div>I'm searching for this word</div>
<div>nothing here</div>
Run codeHide result
0
source

Source: https://habr.com/ru/post/1755044/


All Articles