Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript

How would I pass parameters from the URL to include in a button link with the same parameters?

I'd love some help!

I'm doing a project in which the values "Id" and "Email" are parameters in the URL that a contact lands on. (ex. Webpage.com/page1?Id=12345&Email=test@test.com)

There is a hyperlink to another page on the website that I'd like these values to be passed to and I'm not sure what code I need to put on to do it...

So far, I've done this...

<script> const params = new URLSearchParams(document.location.search); const Id1 = params.get("Id"); const Email1 = params.get("Email"); </script>


Then the link is...

href="https://website.com/Page2/?Id="+Id1+"&Email="+Email1


This is not working, so I'm sure I'm not writing out the hyperlink properly and possibly more... I'm not sure which training to be reviewing for this... I'm in Front End developer with Javascript, but haven't come across this yet...

Any feedback on how to have this pass successfully would be super appreciated!!

2 Answers

Dane Parchment
MOD
Dane Parchment
Treehouse Moderator 11,076 Points

I believe it's not working because you structured the new URL incorrectly. The first parameter of a query string shouldn't be after a forward slash. Instead a question mark should follow the last link in the url and then you pass in the parameters.

So href="https://website.com/Page2/?Id="+Id1+"&Email="+Email1

should be: href="https://website.com/Page2?Id="+Id1+"&Email="+Email1

I believe. This may not work. But pretty sure that's why the url is failing for you.

I got a partial solution from StackOverflow...

Unfortunately, the method you recommended didn't change anything... Here's what I did...

<script>
const params = new URLSearchParams(document.location.search);
const Id1 = params.get("Id");
const Email1 = params.get("Email");
const page2 =()=>window.location.assign(`https://example.com/page2/?Id=${Id1}&Email=${Email1}`);
</script>

Then

<a href="#" onclick="page2()"> Click here </a>

It now works for clicks, but not right-clicks to open in a new tab/window...

I'd love feedback on that if people know what to do there.