htmlpower
htmlpower

Reputation: 169

append on click id from button jquery

Hello friends i am trying to get the id of a button on click whith jquery and append it in the bottom of the href i try with .append but i don´t get

i have this

<button class="btn1" id="5" type="button">click me</button>
<button class="btn1" id="3" type="button">click me</button>

<a href="www.example.com/{id]" class="dellink">Delete</a>

this works but i only need to get the id of the botton

$("btn1").click(function(){
    $(".delllink").attr("href", "http://www.example.com/");
}); 

Upvotes: 3

Views: 1582

Answers (5)

murli2308
murli2308

Reputation: 3004

You can get the id of button on click of it using jQuery's attr method, Also you can replace the href attribute using same attr method.

Documentation to attr is available here

Below code will solve your problem

$('.btn').click(function() {
    var id = $(this).attr('id'); //getting id using jQuery
    $('.dellink').attr('href', 'http://www.example.com/' + id); //changing the href attribute using jQuery.
});

Upvotes: 0

Amar Singh
Amar Singh

Reputation: 5622

HTMl

<a href="www.example.com/" class="dellink">Delete</a>

JS

$("button").click(function(){
    var id = $(this).attr('id');

   // now for url either use static like this
   var p_href = "www.example.com/";

   //or do dynamic 
   var p_href = document.location.hostname+"/";
   $("a.dellink").attr("href", p_href + id);
});

Working Fiddle

Upvotes: -1

Preethi Mano
Preethi Mano

Reputation: 445

Try this

<script>
    $(document).ready(function(){
        $(".btn1").click(function(){
            var href = "www.example.com/" + $(this).attr("id");
            $(".dellink").attr("href", href);
        });
    });
</script>

Upvotes: 1

Sunny
Sunny

Reputation: 3295

Hope this will work for you:

$('button').click(function() { 
    var id = $(this).attr('id');
   $("a").prop("href", "www.example.com/"+id);
});

Upvotes: 1

eisbehr
eisbehr

Reputation: 12452

You could do it this way, if you want to keep the url from the element.

$("button.btn1").click(function() {
    var url = $("a.dellink").attr("href");
    url = url.substr(0, url.lastIndexOf("/") + 1) + $(this).attr("id");

    $("a.dellink").attr("href", url);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button class="btn1" id="5" type="button">click me</button>
<button class="btn1" id="3" type="button">click me</button>
<a href="www.example.com/{id}" class="dellink">Delete</a>

Otherwise you can do it more static too:

$("button.btn1").click(function() {
    $("a.dellink").attr("href", "http://www.example.com/" + $(this).attr("id"));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button class="btn1" id="5" type="button">click me</button>
<button class="btn1" id="3" type="button">click me</button>
<a href="www.example.com/{id}" class="dellink">Delete</a>

Upvotes: 1

Related Questions