Rees Gargi Rees Gargi - 1 year ago 86
Javascript Question

How to add onlick to a link with javascript?

I am using following segment of code to add

to anchor tag but apparently it is not working.

var address_edit = $('.edit-user a').attr('href'));
$('.edit-user a').prop('onclick', 'Popup("address_edit","Edit","900","500");')

What I want:

This is my code on inspect element:

<div class="edit-user">
<a href="">No kidding</a>

This is what I need it to be:

<div class="edit-user">
<a onclick='Popup("address_edit","Edit","900","500");' href="">No kidding</a>

Answer Source

It is not prop, it is attr, because onclick is a attribute, not a property. But I would add a click event listener with jQuery to the element and execute your action there in a callback:

$('.edit-user a').click(function(e) {
    // this stops the 'href' of the anchor from being executed
    // if you want the user to follow the 'href' after click, remove the line

    Popup("address_edit", "Edit", "900", "500");
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download