Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Calling variables from other function

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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)

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading