Lee Giles
Lee Giles

Reputation: 3

Get user input and use as variable in js

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.

Upvotes: 0

Views: 866

Answers (2)

user6887261
user6887261

Reputation:

<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>

Upvotes: 0

Remy Kabel
Remy Kabel

Reputation: 1007

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);
}

Upvotes: 1

Related Questions