+ 1
How to call a function in javascript using onclick of a link
My code(Of course, not working): --HTML-- <a onclick="return putOnMap(this)">Purple Frog</a> --JAVASCRIPT-- function putOnMap(obj){ let name = obj.getAttribute('data-name'); for (let i = 0; i<locations.length; i++) { if(name == locations[i].name){ putOnMapUtil(locations[i].lat, locations[i].lng); alert(name); } } } I have tried href="#" also, but that also hasn't worked!
3 Respostas
+ 3
preventDefault() cancels the redirect
<a href="#" onclick="putOnMap(event, this)"></a>
function putOnMap(event, dom) {
//code
event.preventDefault();
}
+ 1
When I just have an alert("hello") inside your function, clicking on the link calls the function.
Have you checked the console for error messages?
+ 1
Ya, It's working. Sorry to disturb. And my code is this now, can I eliminate href="#"?
<a href="#" onclick="putOnMap(this)" data-name="Purple Frog">Purple Frog</a>