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

154
Visualizações
How to get value from javascript?

I'm trying to get value from js function and pass it to another function or make it global variable. I have variable a3 and I want to get the value from function add() but it's not working.

<!DOCTYPE html>
<html>
    <head>
        <title>Basic Web Page</title>
        <script>
            console.log('hello world!');
        </script>
    </head>
    <body>
       <form>
    a: <input type="number" name="a" id="a"><br>
    
    <button onclick="add()">Add</button>
     <p id="greeting">Greetings</p>

  </form>
  <script src="java.js"></script>
    </body>
</html>
 function add() {
    var a3 = document.getElementById('a').value;
    return a3;    
 }
var a5 = add();
console.log(a5);
about 4 years ago · Juan Pablo Isaza
3 Respostas
Responde à pergunta

0

return false; is important in your case as otherwise after executing your add() function the default handlers for the button will also be executed which will actually reload your page. Here you can find a working example:

function add() {
  var a3 = document.getElementById('a').value;
  console.log('a3='+a3);
  return a3;    
}
var a5 = add();
<form>
  a: <input type="number" name="a" id="a" value="0"><br>
  <button onclick="add(); return false;">Add</button>
  <p id="greeting">Greetings</p>
</form>

about 4 years ago · Juan Pablo Isaza Relatório

0

you can simply write function add() { console.log(document.getElementById("a').value); }

about 4 years ago · Juan Pablo Isaza Relatório

0

Just to add on to the other answer. Your code is running when the script loads. So var a5 is being set not when add() is run, but immediately. Running add() from the onclick is getting the data and returning it, but returning it to nowhere.

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