Reputation: 638
I'm trying to type text into the textbox and when I click the button have it alert me the text. I can't seem to get the variable to work in the function. I'm not sure if "var i = document.getElementById('apple').value;" is correct.
document.querySelector("input[type=button]").addEventListener("click", function(event){
alert(i);});
<form>
Enter:<br>
<input type="text" name="inputbox" id="apple">
<input type="button" name="alert" value="alert">
</form>
<script>
var i = document.getElementById('apple').value;
document.querySelector("input[type=button]")
.addEventListener("click",function(event){
alert(i);});
</script>
Demo: http://codepen.io/michaelaharvey/pen/QyKvme
I also tried:
var i = form.inputbox.value;
but that didn't work either
Upvotes: 2
Views: 61
Reputation: 240858
The problem is that you are storing the element's value in a variable when the DOM loads. Therefore when the click
event is fired, the value
property is an empty string (or whatever the value was when the DOM loaded).
Retrieve the value when the click
event is fired instead:
document.querySelector("input[type=button]").addEventListener("click", function(event) {
var value = document.getElementById('apple').value
alert(value);
});
Upvotes: 3
Reputation: 19772
document.querySelector("input[type=button]")
.addEventListener("click",function(event){
var i = document.getElementById('apple').value;
alert(i);
});
You need to query for the value at the time of click.
Upvotes: 4