Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

152
Views
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 answers
Answer question

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 Report

0

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

about 4 years ago · Juan Pablo Isaza Report

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!