Home > Net >  Make button work after pressing Enter key
Make button work after pressing Enter key

Time:09-29

I have this code, but I want it to complete function "calculate" after clicking enter button. How should it be done? there is no problem with this functionality, but I want to try it with enter button.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="stylesheet" href="style.css">
    <script type="text/javascript" src="index.js"></script>
    <title>Document</title>
</head>
<body>
    <h3>Mini calculator</h3>
   <div >
    <input type="text" name="num1" placeholder="Enter first num"> <br><br>
    <input type="text" name="oper" placeholder="enter operation ( ,-,/,or*)"><br><br>
    <input type="text" name="num2" placeholder="Enter second num"> <br><br>
    <button type="submit"  onclick="calculate()">Calculate</button><br><br>
    <button type="submit" onclick="refreshPage()">Refresh</button>
   </div>
<p id="message" ></p>
</body>
</html>

this is JS source code

function calculate(){
    var a,b,c,num1,oper,num2;
    a=document.getElementsByName("num1")[0].value;
    num1=parseInt(a);
    b=document.getElementsByName("oper")[0].value;
    c=document.getElementsByName("num2")[0].value;
    num2=parseInt(c);
    if(b==" "){
        document.getElementById("message").innerHTML="result is: " (num1 num2);
    }
    else if(b=="-"){
        document.getElementById("message").innerHTML="result is: " num1-num2;
    }
    else if(b=="*")
    {
        document.getElementById("message").innerHTML="result is: " num1*num2;
    }
    else if(b=="/"){
        document.getElementById("message").innerHTML="result is: " num1/num2;
    }
}

function refreshPage(){
    window.location.reload();
} 

CodePudding user response:

You can do what you need with the keypress function

document.addEventListener("keypress", event => {
  if (event.keyCode == 13){
    calculate();
  }
})

keycode 13 works for Enter and Intro

https://jsfiddle.net/kenpy/p8oesf61/3/

CodePudding user response:

You can wrap the inputs in a <form></form>. When you have a form with a button of type="submit" it will automatically submit it when enter key is pressed.

<form id="calculatorForm">
     <div >
        <input type="text" name="num1" placeholder="Enter first num"> <br><br>
        <input type="text" name="oper" placeholder="enter operation ( ,-,/,or*)"><br><br>
        <input type="text" name="num2" placeholder="Enter second num"> <br><br>
        <button type="submit"  onclick="calculate()">Calculate</button><br><br>
        <button type="submit" onclick="refreshPage()">Refresh</button>
     </div>
   </form>

By just doing this the page will reload after submitting the form. To prevent this you can add this to your javascript code and it will not reload the page.

var form = document.getElementById("calculatorForm");
function handleForm(event) { event.preventDefault(); } 
form.addEventListener('submit', handleForm);

Jsfiddle demo https://jsfiddle.net/szndvroe/

CodePudding user response:

If you wrap your inputs and submit button inside of a <form>, you have have Enter work "automagically" onsubmit.

Also, your calculation should occur within its own function.

const messageEl = document.getElementById('message');
const form = document.forms.calculator;

const calculate = (operator, left, right) => {
  switch (operator) {
    case " ": return left   right;
    case "-": return left - right;
    case "*": return left * right;
    case "/": return left / right;
    default: return null;
  }
};

function handleSubmit(event) {
  event.preventDefault(); // Interrupt the event

  const
    num1 =  form.elements.num1.value,
    operator = form.elements.oper.value,
    num2 =  form.elements.num2.value,
    result = calculate(operator, num1, num2);
  
  if (result != null) {
    messageEl.textContent = `Result is: ${result}`;
  }

  return false; // Prevent page navigation
}
form {
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  gap: 1rem;
}
<h3>Mini calculator</h3>
<form name="calculator" onSubmit="handleSubmit(event)">
  <div>
    <input type="number" name="num1" placeholder="Enter first number" step="0.01">
    <input type="text" name="oper" placeholder="Enter operator ( , -, /, or *)">
    <input type="number" name="num2" placeholder="Enter second number" step="0.01">
  </div>
  <div>
    <button type="submit">Calculate</button>
    <button type="reset">Reset</button>
  </div>
</form>
<hr />
<p id="message" ></p>

You could also make your operator input a <select>:

<select name="oper">
  <option value="" disabled selected>Select an operator</option>
  <option value=" "> </option>
  <option value="-">-</option>
  <option value="/">/</option>
  <option value="*">*</option>
</select>
  • Related