I'm trying to have a button that submits a text input, and have that input show as an alert. Here's my code so far (which shows an alert with "undefined"):
<p class="text-right">
<input id="input" type="text" placeholder= "Your Name">
<button id="submit" type="submit"> Submit</button>
</p>
And my Javascript code:
var input = document.getElementById("input").value;
var submit = document.getElementById("submit");
submit.addEventListener("click", function1);
function function1() {
alert(input.value);
}
Kunal Sharma
3692 silver badges20 bronze badges
asked Aug 26, 2016 at 13:11
Sergi
1,2483 gold badges22 silver badges44 bronze badges
1 Answer 1
var submit = document.getElementById("submit");
submit.addEventListener("click", function1);
function function1() {
var input = document.getElementById("input").value;
alert(input);
}
You're alerting input.value.value, but you already have the value in the input variable. EDIT :
var submit = document.getElementById("submit");
var input = document.getElementById("input");
submit.addEventListener("click", function1);
function function1() {
alert(input.value);
}
Which is declaring the input once, and each time the function is called, you alert it's value.
answered Aug 26, 2016 at 13:15
Djaouad
22.8k4 gold badges37 silver badges57 bronze badges
Sign up to request clarification or add additional context in comments.
3 Comments
Sergi
But it comes out blank. I don't seem to be able to get that value to show.
Sergi
That did it, I was thinking it was a matter of positioning, I'm an absolute beginner, was it a matter of scope?
Djaouad
No, the variable input was holding the initial value of the input box which is empty, but it's better to just hold the input box in the variable input, and each time the button is clicked, you alert the value. See the last edit, it's better.
default
element.value.valuedoesn't exist.alert(input). Don't redefinesubmit