How to set up preventDefault on form submit?

I’ve built a basic calculator to learning purposes, using the following JS. It appears to work, or at least it would, if I could get my head around setting up prevent default on the form submit. The console.log() statements and the correct answer flash up very briefly before the page refreshes. I know it lacks this like validating that a numeric value has been submitted at the moment, but I can work on that once I have the basic functionality working properly.

function calcResult() {
  'use strict';
  console.log('calcResult has been called');
  var num1 = parseFloat(document.getElementById('js_firstNum').value);
  var num2 = parseFloat(document.getElementById('js_secondNum').value);
  var opChar = document.getElementById('js_operatorSelect').value;
  var answer;

  switch (opChar) {
    case 'plus':
      answer = num1 + num2;
    case 'minus':
      answer = num1 - num2;
    case 'multiply':
      answer = num1 * num2;
    case 'divide':
      answer = num1 / num2;
      console.log('There has been an error ');
  document.getElementById('js_result').innerHTML = answer;

function init() {
  'use strict';
  document.getElementById('js_submit').addEventListener('click', calcResult, false);
document.addEventListener('DOMContentLoaded', init, false);

Here’s the Codepen for it:

You can bind the event to the form submit, instead of the button click.

function calcResult(e) {
    // do stuff

// do other stuff stuff
// blah
// blah
// blah

document.getElementById('js_calculator').addEventListener('submit', calcResult, false);

This should work.

1 Like

I’ll give it a go… thanks :slight_smile:

Hmm… very close. I get the result now, but when I get focus on the number entry boxes, I’m getting NaN being output before I’ve got any numbers entered, or the submit button clicked.

I’ve updated the pen.

EDIT: Ignore me. I’d missed the change of event type.

1 Like

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.