Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

179
Visualizações
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.

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";
}

about 4 years ago · Juan Pablo Isaza
3 Respostas
Responde à pergunta

0

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)

about 4 years ago · Juan Pablo Isaza Relatório

0

This is likely what you meant to do.

Note I use recommended eventListeners

window.addEventListener("DOMContentLoaded", function() { // when elements are available in page
  const documentLink = document.getElementById('documentLink');
  
  document.getElementById("searchSites").addEventListener("change", function() {
    const chosenSite = this.value;
    if (chosenSite === "Google") { // this could be done nicer with a lookup table
      documentLink.href = "https://www.google.com";
    } else if (chosenSite === "duckduckgo") {
      documentLink.href = "https://www.duckduckgo.com";
    }
  })
  
  documentLink.addEventListener("click", function(e) { 
    if (this.getAttribute("href") === "") { // not set 
      e.preventDefault(); // stop link
      alert("Please select a site first");
    }
  })
})
<select id="searchSites">
  <option value="">Please select</option>
  <option value="Google">Google</option>
  <option value="duckduckgo">duckduckgo</option>
</select><br/>
<a href="" id="documentLink">GO</a>

about 4 years ago · Juan Pablo Isaza Relatório

0

  1. Wrap your code to be executed in DOMContentLoaded event.
  2. Move getDocument function outside of this event listener.
  3. I am assuming you already have a select option event listener and you have a variable named SelectOption with selected value

You may try below code:

<script>
  // Function extracts and returns value from provided parameter
  function getDocumentValue(option) {
    return option.value;
  }

  window.addEventListener('DOMContentLoaded', () => { 
    const documentLink = document.getElementById('documentLink'); // Id is fine if we are sure it wont be duplicated.
    const chosenDocument =  getDocumentValue(SelectOption);

    if (chosenDocument === "Google" ) {
        documentLink.href = "https://www.google.com";
        } else if (chosenDocument === "duckduckgo") {
        documentLink.href = "https://www.duckduckgo.com";
    }   
 })
            
</script>

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda