Reputation: 169
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
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
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);
});
Upvotes: -1
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
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
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