Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

173
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

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 Denunciar

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda