Iam printing some content using php code inside html but, when i tried to click on that div its not calling the function in onClick ??
Here is my php code
echo '<div class="col-sm-12 col-xs-12 " ><div class="row ">';
echo '<div class="col-sm-10" onClick="openUrlInNewTab("'.$myarray['Job']['link'].'");"><h3>';
echo $myarray['Job']['title']."</h3></div></div></div>";
this is resulting html code in "view source" of browser
<div class="col-sm-12 col-xs-12 ">
<div class="row " >
<div class="col-sm-10 " onClick="openUrlInNewTab("www.example.com");" >
<h3>Can you Code? </h3>
</div>
</div>
</div>
and here is my function in html page
function openUrlInNewTab(url) {
// div click is not reaching here
alert(url);
window.open(url, "_blank");
}
4 Answers 4
You should use single quotes.
Instead of
<div class="col-sm-10 " onClick="openUrlInNewTab("www.example.com");" >
you should have
<div class="col-sm-10 " onClick="openUrlInNewTab('www.example.com');" >
If you put double quotes inside double quotes it simple won't work.
So in PHP you should change:
echo '<div class="col-sm-10" onClick="openUrlInNewTab("'.$myarray['Job']['link'].'");"><h3>';
into
echo '<div class="col-sm-10" onclick="openUrlInNewTab(\''.$myarray['Job']['link'].'\');"><h3>';
EDIT
One extra thing. If you want this url open in your browser, you should rather add http:// before www.example.com
Sample working HTML code:
<!DOCTYPE html>
<head>
<meta charset="utf-8" />
</head>
<body>
<div class="col-sm-12 col-xs-12 ">
<div class="row " >
<div class="col-sm-10 " onclick="openUrlInNewTab('http://www.example.com');" >
<h3>Can you Code? </h3>
</div>
</div>
</div>
<script>
function openUrlInNewTab(url) {
// div click is not reaching here
alert(url);
window.open(url, "_blank");
}
</script>
</body>
</html>
1 Comment
onClick="openUrlInNewTab("www.example.com");"
should be
onClick="openUrlInNewTab('http://www.example.com');"
Use single quotes inside the function for the url.
Comments
onClick="openUrlInNewTab("www.example.com");"
should be
onclick="openUrlInNewTab('http://www.example.com');"
the rest is fine
Comments
You know how to use jQuery, right?
$(document).ready(function()
{
$('div').on('click', function()
{
alert('clicked!');
});
});
You can put onclick on div, but it most likely won't work like you're currently doing it because how javascript and php works. (I don't think those noclicks ever get bound)
"www.example.com"with'www.example.com'(single quotes)