Sam Creamer
Sam Creamer

Reputation: 5361

using variable in link in javascript

So I've learned that I can use a button to link someone to another page like this:

$("#something").append("<br><center><input type='button' value='Go' onclick='location.href=\"http://www.google.com\"'></center>");

But let's say I wanted to use a variable as the address, I'm not sure how to do that. What I'm trying to do is something like this:

var url = "http://www.google.com";
$("#something").append("<br><center><input type='button' value='Go' onclick='location.href=url'></center>");

Can someone please correct my error? Thanks

Upvotes: 2

Views: 95

Answers (1)

Adil
Adil

Reputation: 148110

You can concatenate url variable in the string like this,

Live Demo

$("#something").append("<br><center><input type='button' 
value='Go' onclick='location.href=" +url+ "'></center>");

Upvotes: 5

Related Questions