Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

go to link on button click - jQuery

I have a script as below

$('.button1').click(function() {
    document.location.href=$(this).attr('id');
});

the button1 has variable unique ids. on click, the page must redirect to url "www.example.com/index.php?id=buttonid" but now the page is redirecting only to "button id".

I want to add the string "www.example.com/index.php?id=" before the current url. How can I make this possible?

like image 734
Alfred Avatar asked Feb 09 '11 11:02

Alfred


People also ask

How hit an URL on a button click in jQuery?

click(function() { document. location. href=$(this). attr('id'); });

How to trigger click in jQuery?

$(document). ready(function() { $('#titleee'). find('a'). trigger('click'); });

How do you add a link to Onclick?

Using onclick Event: The onclick event attribute works when the user click on the button. When mouse clicked on the button then the button acts like a link and redirect page into the given location. Using button tag inside <a> tag: This method create a button inside anchor tag.


3 Answers

$('.button1').click(function() {
   window.location = "www.example.com/index.php?id=" + this.id;
});

First of all using window.location is better as according to specification document.location value was read-only and might cause you headaches in older/different browsers. Check notes @MDC DOM document.location page

And for the second - using attr jQuery method to get id is a bad practice - you should use direct native DOM accessor this.id as the value assigned to this is normal DOM element.

like image 148
Tom Tu Avatar answered Oct 20 '22 00:10

Tom Tu


$('.button1').click(function() {
   document.location.href='/index.php?id=' + $(this).attr('id');
});
like image 37
Bobo Avatar answered Oct 20 '22 00:10

Bobo


You need to specify the domain:

 $('.button1').click(function() {
   window.location = 'www.example.com/index.php?id=' + this.id;
 });
like image 43
Sarfraz Avatar answered Oct 19 '22 23:10

Sarfraz