How to call a function in javascript using onclick of a link | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 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!

17th Apr 2018, 6:52 PM
Ashutosh
Ashutosh - avatar
3 Answers
+ 3
preventDefault() cancels the redirect <a href="#" onclick="putOnMap(event, this)"></a> function putOnMap(event, dom) { //code event.preventDefault(); }
17th Apr 2018, 8:12 PM
Toni Isotalo
Toni Isotalo - avatar
+ 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?
17th Apr 2018, 7:02 PM
Emma
+ 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>
17th Apr 2018, 7:10 PM
Ashutosh
Ashutosh - avatar