Reputation: 11
I just started learning javascript. I am having undefined error. How can I take user input from HTML form and save it in javascript as global variable that can be used throughout the entire javascript?
html code
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<title>sort</title>
<link rel="stylesheet" href="src1/style.css">
</head>
<body>
<form class="" action="index.html" method="post">
<input id="input" type="text" value="" ><br>
</form>
<button type="button" name ="button" onclick="saveinput()" >submit</button>
<script src = "src1/main.js"></script>
</body>
</html>
javascript code:
var i;
function saveinput(){
i = document.getElementById("input").value;
}
console.log(i)
Upvotes: 0
Views: 1194
Reputation: 3968
Put Your console.log()
inside your function otherwise it would run first and prints undefined
.
The value of i
is undefined until saveinput
function is called.
var i;
function saveinput(){
i = document.getElementById("input").value;
console.log(i);
}
<form class="" action="index.html" method="post">
<input id="input" type="text" value="" ><br>
</form>
<button type="button" name ="button" onclick="saveinput()" >submit</button>
Upvotes: 1