Getting Data From Input Using JavaScript
Solution 1:
You have not defined your id
. Also I guess your input type should be number
.
<input type='number' name="input" id="num">
^^^^^^^^^^^^ ^^^^^^^^
And to alert
its value you need to use
alert(input.value) //.value is used to get value of input
Solution 2:
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)
});
Solution 3:
getElementById()
works on elements with id
attribute. So, as you have not put id
attribute in your input
type, it is not able to find the element with id=num
.
Just add id="num"
in your input
element and then you are good to go.
Post a Comment for "Getting Data From Input Using JavaScript"