Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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>

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

  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>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading