CoeurSys
CoeurSys

Reputation: 1

Get Parameter From URL And Post In Javascript On Click

Thanks for taking time to improve my code. I have a Google Ads link which when clicked contain "Gclid" at the end. URL: https://google.com/?gclid=RandomGclidHere.

My Javascript Code is,

document.getElementById("Australia").onclick = function () {
    location.href = "https://google.com/au.php?gclid=ENTERGCLIDHERE";
};
document.getElementById("New Zealand").onclick = function () {
    location.href = "https://google.com/nz.php?gclid=ENTERGCLIDHERE";
};
document.getElementById("United States").onclick = function () {
    location.href = "https://google.com/us.php?gclid=ENTERGCLIDHERE";
};

I have a drop down on the page which contain 3 options, Australia, New Zealand & USA. The visitor is redirected based on drop-down selection. I want to get the "Gclid" from URL and post the "Gclid" to the URLS through Javascript.

Please guide!

Upvotes: 0

Views: 319

Answers (1)

larsw
larsw

Reputation: 36

If by dropdown you mean a select, I would suggest putting the event listener on the select itself, and using its value:

document.querySelector('select').addEventListener('change', handleCountryChange)

function handleCountryChange(event) {
const countrySelected = event.target.value
const countryDict = { 'australia': 'au', 'country': 'code'}
const countryCode = countryDict[countrySelected]
const gclid = 'ENTERGCLIDHERE'
const googleUrl = `https://google.com/${countryDict}.php?gclid=${gclid}`

window.location.href = googleUrl
}

Having less event listeners is usually desired.

Upvotes: 1

Related Questions