I’m new to JavaScript and currently trying to get variables inside a function to work outside of it and currently met a wall where I can’t seem to get it work.
The scenario is that I want to change the URL via a dropdown form using a combination of Javascript and HTML. If I put the if else statement inside the function it’ll work flawlessly but in my scenario, I need to put it outside of the function and it doesn’t work even after I made the variable global.
I’ve tried several solutions from questions that related to my issue, but it doesn’t seems to work for my scenario.
Here’s the code I’m currently using.
var documentLink = document.getElementById('documentLink');
function getDocument(option) {
chosenDocument = option.value;
}
if (chosenDocument === "Google") {
documentLink.href = "https://www.google.com";
} else if (chosenDocument === "duckduckgo") {
documentLink.href = "https://www.duckduckgo.com";
}
>Solution :
When put your codes directly in the body of the "script" tag, It will execute only once (when the script loads).
You need to put your codes in a place that can run more than once, for example, put it in a function and call that when an event triggers
If you need that "if" block run every time the dropdown value changes you have these options:
1- move your code into the getDocument function
2- move your "if" block into a new function and then call it in the
getDocument function
or 3- move your "if" block into a new function and then assign it to another event coincides with the dropdown event (like dropdown onchange, or dropdown onblur)