0

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.

RianneJ
  • 143
  • 1
  • 11
  • Have you tried the `onsubmit` event on the `
    `? Instead of the `onclick` event on a button?
    – Ismael Miguel Apr 26 '19 at 21:33
  • 1
    There is no variable named `yname` in your code, this should be erroring – Andy Ray Apr 26 '19 at 21:33
  • Andy, that the `name` of the `input` being validated. – David Klinge Apr 26 '19 at 21:37
  • Yes, but you're using it like a variable here. – Ashley Grant Apr 26 '19 at 21:37
  • If you are setting a `required` attribute you don't have to do any of those check. The form will be rejected if the elements marked as required does not meet the specific requirement. As of clearing the form just do `if ( document.forms["myForms"].checkValidity() ) { submit and clear }`. The check validity is redundant but i used it incase someone removed the `required` attribute via the console – 0.sh Apr 26 '19 at 21:39
  • Andy, I see now, it should be in quotes. – David Klinge Apr 26 '19 at 21:43
  • 1
    `document.forms["myForm"][yname][yemail][ymessage].value;` is wrong.... You can not check multiple things at once.... And it is looking for variables.... – epascarello Apr 26 '19 at 21:47

4 Answers4

2

You should really be using the onSubmit handler

As people already pointed at on the comments, there is already a built-in way to verify if all required fields are filled before submitting the form, which is quite more elegant to use. In order to do that, all you need to do is using the onSubmit handler instead of onClick:

<input type="submit" class="contact-form-btn" onClick="return submitForm()" value="Send">

This way, you don't write any code to verify if the user filled all the field properly.

If you still want to use javascript:

The code you wrote does not work as expected because there is not a var called yname on your space. If you really want to do this check via javascript, you could do something like this:

var myForm = document.forms["myForm"];
if (!myForm["yname"].value || myForm["email"].value || myForm["ymessage"].value) {
  alert("Please complete form.");
  return false;
}
Adriano Valente
  • 529
  • 5
  • 15
  • 1
    For your answer to be correct, you have to do `[field].value`, so it work. Because, for example, using `myForm.email` refers to the `email` field. All objects in JavaScript are `truthy` (including `new Boolean(false)`). – Ismael Miguel Apr 26 '19 at 22:17
  • Thank you so much! I changed onClick to the onSubmit handler and replaced the if else statement with just the alert and form reset. Thanks again :) – RianneJ Apr 26 '19 at 23:19
1

You are not correctly accessing the value. Please take a look at my answer below:

document.querySelector('form[name="myForm"]').onsubmit = ev => {
  let yName = document.querySelector('input[name="yname"]').value;
  if (yName) {
    alert("Your message has been sent.");
  } else {
    ev.preventDefault();
    alert("Please complete form.");
  }
};
<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" value="Send">
</form>
Miroslav Glamuzina
  • 4,472
  • 2
  • 19
  • 33
  • And why `document.querySelector('form[name="myForm"]')` when setting an `id` and using `document.getElementById()` is easier? Also, why throw ES6 syntax on someone who's clearly beginning with Javascript? Just wondering. – Ismael Miguel Apr 26 '19 at 21:42
  • @IsmaelMiguel `document.querySelector('form[name="myForm"]')` is so OP could work with the JS above without modifying any HTML. ES6 syntax is in my opinion cleaner and easier to read, plus it adds exposure to people unfamiliar with it (if asked, I would give a pre-ES6 example). – Miroslav Glamuzina Apr 26 '19 at 21:47
  • https://stackoverflow.com/questions/24900875/whats-the-meaning-of-an-arrow-formed-from-equals-greater-than-in-javas <-- the fact that this question has, currently, 171788 views demonstrates that it isn't that clear. And yes, but that introduces something new and confusing: CSS selectors. I think it is better to start by going over the simple first, then introduce the more "advanced". With this, I'm not saying your answer is bad or wrong: it is mostly right on the point. – Ismael Miguel Apr 26 '19 at 22:06
  • 1
    That's a fair point, I guess I should be making my answers more clear, and if I use ES6 syntax I should be better explaining what goes on if needed. – Miroslav Glamuzina Apr 26 '19 at 22:23
0

When your input is blank, the web browser is preventing the form submission because of the required attribute. If you remove it, things should work how you expect. I would encourage you go use the required attribute and HTML form validation. It's much simpler that writing your own.

David Klinge
  • 362
  • 1
  • 9
0

Most likely your problem is that the code stops executing at

var x = document.forms["myForm"][yname][yemail][ymessage].value

This is because, yname, yemail, and ymessage are undeclared variables.

You can access an object using this notation, but the keys sent to the [] operator must be a valid string.

I think what you might want to do is

var name = document.forms["myForm"]["yname"].value
var email = document.forms["myForm"]["yemail"].value
var message = document.forms["myForm"]["ymessage"].value

Also one more thing, inputs on your form should have an id="yname", id="yemail" and so forth.

Example:

<input type="email" name="yemail" class="contact-form-text" placeholder="Your Email" required id="yemail">

Edit: Using name attributes are valid, but as i said above, the code stops executing upon the first use of yname, this is because the variable doesn't exist.

Travis Delly
  • 1,194
  • 2
  • 11
  • 20
  • The problem here is the `required` attribute. And using a `name` attributes are absolutely valid, it's just fallen out of fashion. – David Klinge Apr 26 '19 at 21:40
  • 2
    Sure, i can agree that the using name attributes is valid, but if you look at this code, he is calling yname as a variable, which doesn't exist. The code will stop executing. – Travis Delly Apr 26 '19 at 21:43