0

I have the following HTML:

  <form id="contactInfo" name="contactInfo">
        <label>Name: </label>
        <input type="text" name="name"></input><br/><br/>
        <label>E-mail: </label>
        <input type="text" name="email"></input><br/><br/>
        <label>Message:</label><br/>
        <textarea rows="10" cols="80" name="message"></textarea><br/><br/>
        <input type="submit" name="sendMessage" onclick="messageChecker()"></input>
      </form>

And the following Javascript:

 function messageChecker(){
        let x = document.forms["contactInfo"]["name"].value;
        let y = document.forms["contactInfo"]["email"].value;
        let z = document.forms["contactInfo"]["message"].value;
        if (x=="" || y=="" || z==""){
          alert("Please fill out the indicated field(s).");
          if (x==""){
           document.forms["contactInfo"]["name"].style.border = "1px solid red";
          }
          if (y==""){
           document.forms["contactInfo"]["email"].style.border = "1px solid red";
          }
          if (z==""){
           document.forms["contactInfo"]["message"].style.border = "1px solid red";
          }
      
        }
      
      }

So I want the red border to appear when the form is submitted and a field isn't filled in; it appears for less than a second, then disappears, along with the entered text. How can I get it to stay?

Megan
  • 35
  • 4
  • Sounds like normal behavior. When you submit a form, it will reload the same page unless a different one is specified, which you don't do here. You can prevent the submission of the form in a number of ways, all of which have been covered repeatedly here in other questions. And on a side note, inputs are self-closing, so there's no ``. And you should be using dot notation instead of the very old legacy notation – j08691 Nov 11 '21 at 21:26
  • You should really be using [the HTML5 form/input element type validation for this](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input). The form won't submit if the validation is wrong, and you get automatic little built-in messages to guide to what went wrong. – Andy Nov 11 '21 at 21:31

2 Answers2

0

Because you are performing a form submit, if you want an app style behavior where you are not submitting forms and then reloading the web page then you need to use AJAX types of data submission.

How to use ajax link instead of submit button for form?

T McKeown
  • 12,971
  • 1
  • 25
  • 32
0

maybe use an e.preventDefault() handler to unblock your code?

teafoot
  • 1
  • 1