Reputation: 11474
How to call a JavaScript Function from href tag in html? I have created few tabs. I want when user clicks on any tab the href along with JavaScript function should get called. How can I do it?
<?php if($order == 1){ ?>
<li class="cat-one"><a href= "javascript:loadProducts($categoryId)" > <?php echo $categoryName ?> </a></li>
<?php } ?>
This is my JavaScript:
<script type="javascript" >
function loadProducts($categoryId)
{
alert("Hello World!");
return false;
}
</script>
Upvotes: 13
Views: 88439
Reputation: 101
If you have jquery library you can call with class:
$( ".loadProducts" ).click(function( event ) {
// Default action of the event will not be triggered.
event.preventDefault();
// Get category ID
var categoryId = $(this).attr('data-categoryid');
// TODO
alert("Hello World!");
return false;
});
For:
<li class="cat-one"><a href="#" class="loadProducts" data-categoryid="<?php echo $categoryId;?>" > <?php echo $categoryName ?> </a></li>
Upvotes: 0
Reputation: 833
This should solve your purpose:
<a href="javascript:void(0);" onclick="yourFunction();">Link to Click</a>
Upvotes: 0
Reputation: 4978
Try this
<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: 5128
Don't use the href
, use the onclick
attribute for this
<a href="http://www.example.com" onclick="return confirm('are you sure?')">test</a>
see this example
EDIT(since code added in question): this should call your JS function:
<?php if($order == 1){ ?>
<li class="cat-one">
<a href="javascript:void(0)" onclick="loadProducts(<?php echo $categoryId ?>)">
<?php echo $categoryName ?>
</a>
</li>
<?php } ?>
Upvotes: 8
Reputation: 19862
In the href tag, without specifying a link, specify your javascript function name.
For example
<a href='javascript:myFunction()'> Click Me! <a/>
Upvotes: 22