0

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>
rhysmatthew
  • 13
  • 1
  • 4

2 Answers2

2

You do not need to attach keypress event over input as it is a nature of input type text to submit the form when enter 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>
Rayon
  • 36,219
  • 4
  • 49
  • 76
2

Try this...

<input type="text" id="input" placeholder="Enter your name" onkeydown="if (event.keyCode == 13) { this.form.submit(); return false; }">

It may helpful.

HirenPatel
  • 204
  • 2
  • 8