Home > Net >  How do I make so the window.prompt variables only pop up when a button is clicked?
How do I make so the window.prompt variables only pop up when a button is clicked?

Time:07-13

I'm trying to make it so the window prompts only pop up when a button is clicked.

When I run it, I get "illegal invocation" and the window prompts pop up every time I save a change in my code pen. How can I fix this?

function problemSolve() {
  let a = window.prompt("first number: ");
  let b = window.prompt("second number: ");
  let method = window.prompt("Choose how to solve: ");
  switch (method) {
    case ('divide'):
      console.log(a / b);
      break;
    case ('multiply'):
      console.log(a * b);
      break;
    case ("add"):
      console.log(a   b);
      break;
    case ("subtract"):
      console.log(a - b);
      break;
    default:
      break;
  }
  document.getElementById('bgnBtn').onclick = alert;
};
problemSolve();
<script src="function problemSolve() {.js"></script>
<button id="bgnBtn">Start calculator</button>

CodePudding user response:

  1. Your src is incorrect - it should be something like <script src="problemsolver.js"></script>
  2. You cannot just use alert as an event handler.

You meant to do this

document.getElementById('bgnBtn').onclick = problemSolve;

if code is after the button

but I recommend this:

window.addEventListener("DOMContentLoaded",function() {
  document.getElementById('bgnBtn').addEventListener("click",problemSolve);
});

function problemSolve() {
  let a = window.prompt("first number: ");
  let b = window.prompt("second number: ");
  let method = window.prompt("Choose how to solve: ");
  switch (method) {
    case ('divide'):
      console.log(a / b);
      break;
    case ('multiply'):
      console.log(a * b);
      break;
    case ("add"):
      console.log(a   b);
      break;
    case ("subtract"):
      console.log(a - b);
      break;
    default:
      break;
  }

};
window.addEventListener("DOMContentLoaded",function() {
  document.getElementById('bgnBtn').addEventListener("click",problemSolve);
})
<script src="function problemSolve() {.js"></script>
<button id="bgnBtn">Start calculator</button>

  • Related