0

Can someone please explain to why nothing happens when I press enter when I am in the
the textbox?

<script>
function buttonCode(){
  alert("Button code executed.") }

var input = document.getElementById("userinput");

input.addEventListener("keyup", function(event) {
if (event.keyCode === 13){
event.preventDefault();
document.getElementById("button1").click();
    }
  });
</script>


<body>
  <input id="userinput" type ="text">
  <button id="button1"
          onclick = "buttonCode()"
          >
    Button
  </button>
</body>
David
  • 208,112
  • 36
  • 198
  • 279
Vic4561
  • 11
  • 4
  • 1
    What do you **expect** to happen? – Quentin Nov 19 '19 at 17:23
  • @Quentin: The edit removed/solved the problem. His code simply isn't finding the element because it executes before the element exists, which isn't an issue in SO code snippets by design. – David Nov 19 '19 at 17:25
  • Hmm looks like T.J. Crowder closed this as the same thing as I did and then reopened it. Pretty sure this is the issue though. @Vic4561 let us know if using a ready event or moving the script to the bottom of your html doesn't fix – Patrick Evans Nov 19 '19 at 17:28
  • 1
    @T.J.Crowder that function has a closing `}` so it wouldnt have wrapped the listener setup – Patrick Evans Nov 19 '19 at 17:32
  • @PatrickEvans - Ah, thanks. Vic - ***Please*** don't use that bracing style. Someone seems to be teaching it to people, I can't imagine why, but it's ***very*** hard to read and hard to edit (think how much work you have to do to move lines around in the block). – T.J. Crowder Nov 19 '19 at 17:34
  • By far the easiest way to get this to do what you want, assuming what you want is a form submission, is to remove all of the code and put the `input` and `button` in a `form`. Then, since there's only one `input`, pressing Enter in it will trigger a form submission. – T.J. Crowder Nov 19 '19 at 17:36

1 Answers1

-1
<body>
  <input id="userinput" type ="text">
  <button id="button1" onclick = "buttonCode()" >
    Button
  </button>

  <script>

function buttonCode(){
  alert("Button code executed.") }

var input = document.getElementById("userinput");

input.addEventListener("keyup", function(event) {
if (event.keyCode === 13){
event.preventDefault();
document.getElementById("button1").click();
    }
  });
</script>
</body>

Try this need to write script after html elements

Saurabh Yadav
  • 3,303
  • 1
  • 10
  • 20