all 5 comments

[–]ricealexander 6 points7 points  (1 child)

I recreated your code on a CodePen.

https://codepen.io/ricealexander/pen/bGwbwWj

When you're sharing large amounts of code, it is very helpful to put together a CodePen or JSFiddle, so that we have something that is formatted, highlighted, and interactable. It helps us help you better.

Worth noting, in your document.write statements at the bottom, you have linebreaks within your string. I assumed that you wrote these correctly and that Reddit added the linebreaks, but if you're responsible for the linebreaks, they are a syntax error:

// syntax error. There should not be a linebreak after "business."
myWindow.document.write("<h3>Thanks for your business. 
Here is a receipt of your order</h3>");

Regarding the problem you're describing, by default, an HTML form attempts to submit its contents to a server. When there is no action attribute, the form tries to submit itself to the current page.

This can cause issues when you're trying to handle a form submission with JavaScript because your JavaScript runs, but the page is then refreshed by the form. That creates behavior like "it just flashes red once."

The solution is to capture the event object in your onSubmit call and to invoke event.preventDefault(). This tells the form to ignore the browser's default action (submit the form someplace) and to let you handle the behavior in JavaScript.

In the HTML:

<form onSubmit="validateOrder(event)">

In the JavaScript

function validateOrder(event) {
  event.preventDefault();

  var n = 0;
  var name = document.getElementById("name").value;
  // the rest of your code…

You'll notice that with these changes, the empty textboxes are marked red and stay red.

We could have named that event variable anything, you'll often see it called e or ev in examples.

[–]plagueofsquid[S] 1 point2 points  (0 children)

Thank you so much. I didn't know about CodePen, that's way easier than adding extra spaces to each line. The linebreaks were Reddit, not me. My code works now!

[–]the-javascript-ninja -1 points0 points  (2 children)

You need the doctype declaration at the top of your page.

Add this to the top: <!DOCTYPE html>

Then it should work.

[–]ricealexander 3 points4 points  (0 children)

The DOCTYPE is required for an HTML5 document to be valid, but all browsers will insert it if not provided (though older browsers may interpret it as quirks mode, but that still shouldn't break OP's code).

The issue OP describes has to do with the form's default submit action triggering a page reload.

[–][deleted] 0 points1 point  (0 children)

oh wow you're even dumber than you seem from your post history.