innocent rock
innocent rock

Reputation: 129

How to add onclick to a link with javascript?

I am using following segment of code to add onclick 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="example.com/nokidding">No kidding</a>
</div>

This is what I need it to be:

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

Upvotes: 0

Views: 141

Answers (6)

Jax Teller
Jax Teller

Reputation: 1467

Add click event like this :

$('.edit-user a').click(function(e) {
    e.preventDefault();
    Popup("address_edit","Edit","900","500");

    // I don't know if you need to redirect after popup open
    window.location.href = "example.com/nokidding";
})

Upvotes: 1

KanUXD
KanUXD

Reputation: 707

This should work :)

$(document).ready(function(e){
$(".link").attr('onclick','Popup("address_edit","Edit","900","500");');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<a class="link" href="example.com/nokidding">No kidding</a>

Upvotes: 0

T&#237;nh Ng&#244; Quang
T&#237;nh Ng&#244; Quang

Reputation: 4652

Please confirm my demo :

$('.edit-user a').click(function(e) {
    e.preventDefault();
    var href = $(this).attr('href');
    console.log(href);
    //Popup(href, "Edit", "900", "500"); //open popup
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="edit-user">
     <a href="example.com/nokidding">No kidding</a>
 </div>

Upvotes: 0

Deepak Dholiyan
Deepak Dholiyan

Reputation: 1912

You need to use dynamic biding for this because you are creating element dynamically. Use below

$(document).on('click', '.edit-user a', function() {
Popup("address_edit", "Edit", "900", "500");
});

Upvotes: 0

Araknid
Araknid

Reputation: 476

It's attr not prop. You can handle it like this:

$('.edit-user a').on('click', function() {
    Popup("address_edit", "Edit", "900", "500");
});

Upvotes: 0

eisbehr
eisbehr

Reputation: 12452

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
    e.preventDefault();

    Popup("address_edit", "Edit", "900", "500");
});

Upvotes: 0

Related Questions