In my code I wish to be able to press enter and it to press my input button. At the moment I am having no luck, any suggestions for my code? Thanks,
<form>
<input type="text" id="input" placeholder="Enter your name">
<input type="button" id="button" value="enter">
</form>
<h1 id="output">Please Complete Form</h1>
<script>
var button = document.getElementById("button");
var input;
var output;
button.addEventListener("click", clickHandler, false);
input.addEventListener("keypress", handle, false);
function clickHandler () {
input = document.getElementById("input");
output = document.getElementById("output");
output.innerHTML = input.value;
}
function handle(e){
if(e.keyCode==13){
document.getElementById('button').click();
}
}
</script>
You do not need to attach
keypress
event over input as it is a nature of input type text to submit the form whenenter
key is pressed.
Note: variable input
is undefined when addEventListener
is attched to it hence it produces error.
Try this:
var button = document.getElementById("button");
var input = document.getElementById("input");
button.addEventListener("click", clickHandler, false);
function clickHandler() {
var output = document.getElementById("output");
output.innerHTML = input.value;
}
<form>
<input type="text" id="input" placeholder="Enter your name">
<input type="button" id="button" value="enter">
</form>
<h1 id="output">Please Complete Form</h1>