go to link on button click - jQuery

Alfred picture Alfred · Feb 9, 2011 · Viewed 114k times · Source

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?

Answer

Tom Tu picture Tom Tu · Feb 9, 2011
$('.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.