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);
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>
you can simply write
function add() { console.log(document.getElementById("a').value); }
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.