[Solved] Getting data from input using JavaScript


There are more than one problems with your code

1) You have to close the bracket of your function
it should be

 document.getElementById('btn').onclick = function(){
    input = document.getElementById('num');
        alert(input); //To check what value is outputted
}  

2)

input = document.getElementById('num');

The getElementById() method returns the element that has the ID
attribute with the specified value.

so ID attribute is essential here and in your code there is no ID attribute defined so you have to defined it first

like

<input type="number" id="num" name="input">

3) document.getElementById('num'); does not return the value of input field
it returns object
so if you want value then use the following code

document.getElementById('num').value;

4) your input type="number"

for the desired output you can use following code

Choose a number between 1 and 5 <input type="number" name="input" id="myid">

<button id="btn">Click me!</button>

JS

    var myButton = document.getElementById("btn");
myButton.onclick = function()
{
         alert(document.getElementById("myid").value); //where does id come from?
}

The above method is pure JS if you need jquery method you can refer below

$( "#btn" ).click(function() {
  var input=$("#myid").val();
    alert(input)
});

solved Getting data from input using JavaScript