tags:

views:

137

answers:

2

There's a great tutorial on IBM's website which walked me through a simple search/results list using jQuery,PHP and Ajax.

I was able to make it work and it's really cool.

One problem. I want the results to be hyperlinks and I can't get any java script to run on the results.

Here is the script I have (includes what was in the tutorial plus the additional script necessary to ovverride the hyperlink, click behavior):

<script type='text/javascript'>
$(document).ready(function(){
$("#search_results").slideUp();
$("#search_button").click(function(e){
e.preventDefault();
ajax_search();
});
$("#search_term").keyup(function(e){
e.preventDefault();
ajax_search();
});
$("a").click(ClickInterceptor);
});

function ajax_search(){
$("#search_results").show();
var search_val=$("#search_term").val();
$.post("./find.php", {search_term : search_val}, function(data){
if (data.length>0){
$("#search_results").html(data);
}
})
}

function ClickInterceptor(e)
{
window.alert("Hellow World!");
return false;
}
</script> 

If i put the following html under the <body> tag:

<a href="test">this will work</a>

That will display the alert window.

However, if I change the results to hyperlinks (found in find.php, listing 7 from the tutorial):

$string .= "<a href=\"test\">".$row->name."</a> - "; 

It does not work.

Any idea on how to fix this?

+2  A: 

The click function binds when it is run. You need to change it to a live binding.

$("a").live("click", ClickInterceptor);

Or you can just bind it when you update the search results by putting the following after $("#search_results").html(data):

$("#search_results a").click(ClickInterceptor);
Brian McKenna
well, apparently, I don't have enough reputation to vote up. But swapping to live binding did the trick. I'm sure the others would have too.tyvm!
ray023
Instead of voting up, you are meant to "accept" the answer by clicking the check mark underneath the arrows to the left. Here is more information: http://meta.stackoverflow.com/questions/5234/accepting-answers-what-is-it-all-about
Brian McKenna
A: 

The problem is pretty simple actually, $("a").click(ClickInterceptor); will only look for items that currently exist in the DOM. All you need to do is change that line to this:

$("a").live("click", ClickInterceptor);

I'd also advise taking the time to read more about jQuery's Events/live.

Dereleased