0

I am new to JavaScript and tend to get stuck with some problems. I was trying to create a custom validation for a form, which consists from 4 inputs, but the code doesn't work for me. Does anyone have any ideas how can I fix it? Here is just one of the inputs:

          <div class="inputWrapper">
            <input class="formInput required type="text" name="Email" id="Email" placeholder="Email Address"/>
            <img class="errorImg hidden" src="/images/icon-error.svg" />
            <div id="emailError" class="errorMessage hidden">
              <i>Email cannot be empty</i>
            </div>
          </div>

I also have two divs that should appear, when the input is submitted with error, before that they have a class "hidden" with display none.

"use strict";

const formInput = document.querySelector(`.formInput`);
const errorImg = document.querySelector(`.errorImg`);
const errorMessage = document.querySelector(`.errorMessage`);

const input = formInput.nodeValue;

const errorOccured = function () {
  errorMessage.classList.remove(`hidden`);
  errorImg.classList.remove(`hidden`);
};

form.addEventListener("submit", function () {
  if (input === ``) {
    errorOccured();
  }
});

This is how the page looks like itself:

1
  • 1
    Pass in the EventObject and EventObject.preventDefault() in your submit Listener. And I wouldn't use Template Literals unless you need something to be parsed, as it just takes longer to process. Commented Dec 28, 2020 at 23:42

1 Answer 1

1

You should read input value in the event listener function

let form = document.querySelector("#form1");
form.addEventListener("submit", function (e) {
    const input = formInput.value;
    if (input === '') {
        errorOccured();
        e.preventDefault();
    }
});
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.