I have the contents of a php file loaded via Ajax that contains HTML and JavaScript. I have a button:

<button class="search_button">Search</button>

And I have a script underneath that will update the documents hash from a jQuery function

<script type="text/javascript">
  $(".search_button").click(function() {
    var searchTerm = $('#search_box').val();         
    document.location.hash="searchTerm";
    return false;
  });
</script>

This code works when I run the php file separately, but when loading this page from an Ajax call, the function no longer runs. In firebug the script is not present so I am assuming I cannot load a script in using this method. I tried also putting the JavaScript snippet instead a header for the whole website, but this failed also.

I was also thinking perhaps the function has to be declared when there is a search_button class already present, but it was structured in this way when I previously had them in one file (that was retrieved via Ajax) to no avail so I'm confused as to the problem.

Accepted Answer

You can include it globally with a live event:

  $(".search_button").live('click', function() {
    var searchTerm = $('#search_box').val();         
    document.location.hash="searchTerm";
    return false;
  });

jQuery will automatically evaluate script blocks, you cannot see the function in the HTML because it has been stripped out. However it should have already run. The problem is most likely timing. You could do something like

setTimeout(function(){  
    $(".search_button").click(function() {
        var searchTerm = $('#search_box').val();         
        document.location.hash="searchTerm";
        return false;
    });
}, 500);

So that when the script is loaded it waits to be executed (hopefully giving jquery time to update the DOM with the new element).

Written by Josiah Ruddell
This page was build to provide you fast access to the question and the direct accepted answer.
The content is written by members of the stackoverflow.com community.
It is licensed under cc-wiki