0

I have a function and some code:

function findMember(str) {
        // console.log('search: ' + str);

        $.post("includes/search.php", {
            search: str,
        }, function(data, status) {
            // console.log(data);
            $('#creatorSearchMain').html(data);
        });

    }

    $('#creatorSearchInput').keyup(function() {
        var target = $('#creatorSearchInput');
        findMember(target.val()); //remove and uncomment other if want to wait before request
    });

This selects the text from an input and uses it with .post to query the database to search for a user with the name searched. The .post returns html code that is added to a div.

In that html that is returned there is a button:

<button class="followButton " type="submit" value="1">Follow</button>

When that button is clicked it runs another javascript function.

This all works perfectly except for when I try and click the button after I have used .html to add the html returned to the div.

To clarify, the button works when the page is first loaded and it is there but when I put it back there with the new results it does not seem to be picked up by the javascript.

This is what I am using to activate the onclick button function:

$('.followButton').on("click", function() { 
#code in here
});

Thanks in advance!

Shaunak D
  • 20,588
  • 10
  • 46
  • 79
rpbodley
  • 73
  • 2
  • 8

2 Answers2

7

Your button is being added dynamically, use event delegation using on() for adding click handlers to it,

$("#creatorSearchMain").on("click",".followButton", function() { 
    #code in here
});

*The selector before on(), $("#creatorSearchMain") here, should be a static element.

Shaunak D
  • 20,588
  • 10
  • 46
  • 79
2

Use that code:

$('#creatorSearchMain').on("click", '.followButton', function() { 
    #code in here
});