vendredi 26 avril 2019

If Else Statement is not being executed

I have a contact form, which includes required fields. I have written an If else statement so that if the required fields are empty, the form will not be sent and if it is, the form will be sent and cleared. The If part of the statement is executing, but the else doesn't seem to be. I am still learning Javascript so i have probably done something incorrectly.

I have tried looking at looking at layouts of If else statements and amending mines, but this has not helped.

<form name="myForm" class="contact-form" 
action="mailto:someone@example.com" method="post" enctype="text/plain">
    <input type="text" name="yname" class="contact-form-text" 
placeholder="Your Name" required>
    <input type="email" name="yemail" class="contact-form-text" 
placeholder="Your Email" required>
    <textarea class="contact-form-text" name="ymessage" placeholder="Your 
Message" required></textarea>
    <input type="reset" class="contact-form-btn-reset" value="Reset">
    <input type="submit" class="contact-form-btn" onClick="return 
submitForm()" value="Send">

    <script>
      function submitForm() {
        var x = document.forms["myForm"][yname][yemail][ymessage].value;
        if (x == "") {
          alert("Please complete form.");
          return false;
        } else {
          alert("Your message has been sent.");
          var frm = document.getElementsByName('myForm')[0];
          frm.submit();
          frm.reset();
          return false;
        }
      }
    </script>
  </form>

When the submit button is pressed, i'm expecting the form to submit with an alert and clear (if all fields are completed), if all fields aren't completed i expect the form to not submit.

Aucun commentaire:

Enregistrer un commentaire