28

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?

Syscall
  • 19,327
  • 10
  • 37
  • 52
Alfred
  • 21,058
  • 61
  • 167
  • 249

5 Answers5

70
$('.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.

Tom Tu
  • 9,573
  • 35
  • 37
  • +1 for being the first to suggest window.location and this.id, I went with my answer quickly without them ;) – Sarfraz Feb 09 '11 at 12:03
6

You need to specify the domain:

 $('.button1').click(function() {
   window.location = 'www.example.com/index.php?id=' + this.id;
 });
Sarfraz
  • 377,238
  • 77
  • 533
  • 578
  • href is unnecessary and look at my answer to see more info on things that could have been done better – Tom Tu Feb 09 '11 at 11:57
  • @Tom Tu: Yeah good suggestion, updated the code. You need to consider the down vote, it wasn't wrong any way. – Sarfraz Feb 09 '11 at 11:59
6
$('.button1').click(function() {
   document.location.href='/index.php?id=' + $(this).attr('id');
});
Bobo
  • 595
  • 5
  • 18
2

Why not just change the second line to

document.location.href="www.example.com/index.php?id=" + $(this).attr('id');
Chowlett
  • 45,935
  • 20
  • 116
  • 150
0

you can get the current url with window.location.href but I think you will need the jQuery query plugin to manipulate the query string: http://plugins.jquery.com/project/query-object

Guillaume86
  • 14,341
  • 4
  • 53
  • 53