how do i get a variable value from the <input type="number" > and use it in the script part?

Viewed 14

Here is my code

<html>
<head>
    head
    <title>title</title>
</head>
<script>
    var val1 = parseInt(document.getElementById('input1'));
    function bytton()
    {
        window.alert(val1);
    }
</script>
<body>
    <br>
    <input type="number" id="input1"/>
    <br>
    <button type="button" onclick="bytton()">value of val1</button>
</body>
</html>

It runs properly without any problem.

At the input field i write a number in it and then click on the button but then it displays that the value is NaN,I think the value is not getting assigned to val1.

2 Answers

You should change your code like this.

<html>
<head>
    head
    <title>title</title>
</head>
<script>
    function bytton()
    {
        var val1 = document.getElementById('input1').value;
        window.alert(val1);
    }
</script>
<body>
    <br>
    <input type="number" id="input1"/>
    <br>
    <button type="button" onclick="bytton()">value of val1</button>
</body>
</html>

<html>
<head>
    head
    <title>title</title>
</head>
<script>
    function bytton() {    
    window.alert(document.getElementById("input1").value);
    }
</script>
<body>
    <br>
    <input type="number" id="input1"/>
    <br>
    <button type="button" onclick="bytton()">value of val1</button>
</body>
</html>

Related