If I copy this exactly into my code, it says test undefined. I've tried the code from at least five pages like this and they all give an error. I need to get a number from the user and assign it to a variable in my script.js and then be able to use that variable.
2 Answers
I think I know what your problem is. I've resimulated it in this fiddle.
Most likely your problem is that you put that piece of code in the head. This causes the function test() to be undefined to any HTML. Instead you should include the function in the script tag within the body. So to compare, this will not work and give the error test is undefined:
<html>
<head>
<script>
function test() {
var value = document.getElementById('userInput').value;
alert(value);
}
</script>
</head>
<body>
<input type="text" id="userInput" placeholder="Give me a value">
<button onclick="test();">Submit</button>
</body>
</html>
Whereas this will:
<html>
<head>
</head>
<body>
<input type="text" id="userInput" placeholder="Give me a value">
<button onclick="test();">Submit</button>
<script>
function test() {
var value = document.getElementById('userInput').value;
alert(value);
}
</script>
</body>
</html>
Separating this in an HTML file and a script file it would look like this (tested and working):
test.html:
<html>
<body>
<script src="test.js"></script>
<input type="text" id="userInput" placeholder="Give me a value">
<button onclick="test();">Submit</button>
</body>
</html>
test.js:
function test() {
var value = document.getElementById('userInput').value;
alert(value);
}
4 Comments
Lee Giles
Can I have it in my script.js file? I never add css or js to the html. In my js file is where I have it.
Remy Kabel
It's fine but then also make sure to include the script file in the body, not the head.
Remy Kabel
Edited the answer. I have this setup working in my browser right now.
Lee Giles
Thanks, I will try again.
<input type="text" id="txt" />
<button id="sub">submit</button>
<script>
const btn =document.getElementById("sub");
let val;
btn.addEventListener("click",get_val);
function get_val(){
val =
document.getElementById("txt").value;}
//Use it as you want
console.log(val);
</script>
3 Comments
Lee Giles
This gives the error "Uncaught SyntaxError: Missing initializer in const declaration"
Lee Giles
Thanks, I will try again.