2

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

1
  • 2
    You have to put the line that gets the value inside the event handler for click. Right now it only gets the value on pageload, not everytime you click Commented Dec 24, 2015 at 23:47

2 Answers 2

4
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.

Sign up to request clarification or add additional context in comments.

Comments

3

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:

Updated Example

document.querySelector("input[type=button]").addEventListener("click", function(event) {
  var value = document.getElementById('apple').value
  alert(value);
});

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.