Forum Moderators: coopster

Message Too Old, No Replies

PHP concatenating a href and onclick event trouble

Trouble embedding javascript function to be used in an oncilck event

         

LyricalPanda

11:45 pm on Apr 12, 2009 (gmt 0)

10+ Year Member



Hello, heres a sample code that I'm working with:

$output = "<table>";
$output.= "<tbody>";
foreach($results as $result)
{
$output.= "<tr>";
$output.= "<td>".date("m/d/y",$result['datestamp'])."</td>";
$output.= "<td><a href='" . "' target='_self'>{$result['title']}</a></td>";
$output.="</tr>";

}
$output.= "</tbody>";
$output.= "</table>";

Simple enough. However, in each of those a href links, I want to have an onclick event sent to a javascript function, do_ajax. Specifically, I want to be able to send the function an ID number, so that the javascript can update the page with the click (without having to refresh it). So, say, the 4th item will have an ID = 4, and I want the javascript to be able to intercept that number and do its thing. Getting to syntax just write seems to be killing me though -- I'm fairly new to web programming (Java/C# programmer).

Thanks!

blang

1:27 am on Apr 13, 2009 (gmt 0)

10+ Year Member



You could do it inline, e.g.

$output.= '<td><a href="" target="_self" ';
$output.= 'onclick="do_ajax('.$result['id'].');">';
$output.= $result['title'] .'</a></td>';

Which gives you something like


<a href="" target="_self" onclick="do_ajax(4);">title</a>

You could also assign a class to each anchor element, and use a DOM function in a SCRIPT element to parse through and find the anchors that match this specific class, then assign the click event to those anchor tags.

LyricalPanda

1:53 am on Apr 13, 2009 (gmt 0)

10+ Year Member



I was hoping to get away from having to view the DOM -- I do appreciate the quick reply. With the code you linked, however, it is still linking back to the same page (even after taking out the target="_self"). How do I stop this so the onclick command is called rather than a redirect to the same page?

Thanks

blang

2:16 am on Apr 13, 2009 (gmt 0)

10+ Year Member



Well, get rid of the target attribute and either return false at the end of the inline onclick handler or in your do_ajax call, e.g.

<a href="" onclick="do_ajax(4); return false;">title</a>