-1

How do i execute function "myanswer1()", when the user presses enter inside the text field? here is my code:

function myanswer1() {
  var x = document.getElementById("myText").value;
  var y = x*x;
  document.getElementById("answersq").innerHTML = y;
  }
<div class="holder" align="center" id="sq">
  <h1 align="center" class="write"><u>Square Finder</u></h1>
  <p align="center">
<input id="myText" type="text" placeholder="enter a number here">
<button onclick="myanswer1()" class="button1">Try it</button><p class="ans" id="answersq"></p>

The function should be executed only when the user is clicking enter inside the text field.

Liam
  • 27,717
  • 28
  • 128
  • 190

2 Answers2

0

Use the submit event, then no need to test

I added a few extras. It is recommended to use eventListener over an inline event handler

const fld = document.getElementById("myText")
const answer = document.getElementById("answersq");

document.getElementById("myForm").addEventListener("submit", function(e) {
  e.preventDefault(); // stop submission
  const x = fld.value;
  answer.innerHTML = x * x;
  fld.select(); // focus and select the field content
})
fld.select(); // focus and select the field content
<form id="myForm">
  <div class="holder" align="center" id="sq">
    <h1 align="center" class="write"><u>Square Finder</u></h1>
    <p align="center">
      <input id="myText" type="text" placeholder="enter a number here">
      <button class="button1">Try it</button>
    </p>
    <p class="ans" id="answersq"></p>
  </div>
</form>
mplungjan
  • 169,008
  • 28
  • 173
  • 236
-1

You can use jQuery to detect the keypress event (whenever any key is pressed), and then check if the pressed key is the enter key (which has the number 13 assigned). Check Phong's answer to see how this is done in vanilla JavaScript (without jQuery).

$("#myText").on('keypress',function(e) {
    if(e.which == 13) {
        myanswer1();
    }
});

function myanswer1() {
  var x = document.getElementById("myText").value;
  var y = x*x;
  document.getElementById("answersq").innerHTML = y;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<div class="holder" align="center" id="sq">
  <h1 align="center" class="write"><u>Square Finder</u></h1>
  <p align="center">
<input id="myText" type="text" placeholder="enter a number here">
<button onclick="myanswer1()" class="button1">Try it</button><p class="ans" id="answersq"></p>
Axel Köhler
  • 911
  • 1
  • 8
  • 34