Reputation: 11474
How do I call a JavaScript function from href tag in html? I've created a few tabs and when a user clicks on one of them the href along with JavaScript function should get called.
<?php if($order == 1){ ?>
<li class="cat-one">
<a href="javascript:void(0)" onclick="loadProducts(<?php echo $categoryId ?>)">
<?php echo $categoryName ?>
</a>
</li>
<?php } ?>
This is my JavaScript:
function loadProducts($categoryId)
{
alert("Hello World!");
return false;
}
Why doesn't the alert trigger in my function? I am running 2 jQueries on the same page.
Upvotes: 0
Views: 198
Reputation: 99
From what I can tell without actually running this code, you can fix a few semi-colons on lines 3 and 4, change the href, and put the parameter for loadProducts
in quotes. Try this:
<?php if($order == 1){ ?>
<li class="cat-one">
<a href="#" onclick="loadProducts('<?php echo $categoryId; ?>')">
<?php echo $categoryName; ?>
</a>
</li>
<?php } ?>
Let me know if it works out for you.
Upvotes: 0
Reputation: 4978
May be your php script has some errors, Try this example also.
<html>
<body>
<script type= "text/javascript">
function loadProducts(catid){
alert(""Hello World!"+catid);
return false;
}
</script>
<?php if($order == 1){ ?>
<li class="cat-one">
<a href="javascript:void(0)" onclick="loadProducts(<?php echo $categoryId ?>)"><?php echo $categoryName ?> </a>
</li>
</body>
</html>
Upvotes: 0
Reputation: 669
From your script above I really don't see nothing wrong with the JavaScript. Try debugging your PHP first to see if the expected value like ($categoryId) is exactly what you expect to be.
Your are missing something also from the script tag
<script type="text/javascript">
// Your script goes here...
</script>
Upvotes: 0
Reputation: 98
I just checked the JavaScript, you make a mistake while declaring script tag, the correct code is below
<script type="text/javascript" >
function loadProducts($categoryId)
{
alert("Hello World!");
return false;
}
</script>
Upvotes: 0
Reputation: 6740
Try:
<script type="javascript" >
function loadProducts(categoryId)
{
alert("Hello World!" + categoryId);
return false;
}
</script>
And also:
<a href="#" onclick="loadProducts(<?php echo $categoryId ?>); return false;" >
<?php echo $categoryName ?>
</a>
Upvotes: 0
Reputation: 49919
What if you try this:
<a href="#" onclick="loadProducts(<?php echo $categoryId ?>); return false;">
Upvotes: 2