@ligisayan

Хочу сделать валидацию и отправку формы на чистом css+js, но почему получаю ошибки?

Всем привет!
Есть форма отправки. Пытаюсь сделать валидацию и иммитацию отправки формы (со страницы не должно перебрасываться, а просто над кнопкой отправить выводится текст "отправка") с помощью чистого js не используя сторонних библиотек, но что-то пока совсем запутался. Что не так: Фидл

  1. валидация полей, кроме текстовой области отрабатывает не верно. При вводе первого символа в текстовых полях тут же появляется зеленая иконка, а не по окончанию ввода пользователем и проверки введенных данных.
  2. функция submit не срабатывает вообще - почему?
  3. после нажатия на кнопку перезагружается страница. Как это можно предотвратить и выводить в простом лейбле надпись отправлено?
<link href="https://use.fontawesome.com/releases/v5.1.0/css/all.css" rel="stylesheet" />
<form name="sentMessage" id="form" action="#">
  <p><input type="text" placeholder="Name" name="name"><i class="fas fa-check-circle"></i></p>
  <p><input type="email" placeholder="Email" name="email"><i class="fas fa-check-circle"></i></p>
  <p><input type="tel" placeholder="Phone" name="phone"><i class="fas fa-check-circle"></i></p>
  <p><textarea placeholder="Message" name="message" id="form-control" rows="3"></textarea><i class="fas fa-check-circle" id="circle-ok"></i></p>
  <label id="submitting"></label>
  <input type="submit" value="Send Message" />
</form>

var textarea = document.getElementById('form-control');
textarea.addEventListener('input', function(e) {

  if (this.value != '') {
    document.getElementById("circle-ok").style.display = "block";
  } else {
    document.getElementById("circle-ok").style.display = "none";
  }
});

var textarea = document.getElementById('form-control');
textarea.addEventListener('input', function(e) {

  if (this.value != '') {
    document.getElementById("circle-ok").style.display = "block";
  } else {
    document.getElementById("circle-ok").style.display = "none";
  }
});

document.getElementById("form").onsubmit = function(event) {
	  if (whatever == true) {
	    event.preventDefault();
	    document.getElementById("submitting").innerHTML = "Submitting...";
	  }
	};

form input,
form textarea {
  box-sizing: border-box;
  width: 100%;
  background: transparent;
  border: 1px solid #8e908f;
  font-size: 20px;
  color: #fff;
}

form p {
  position: relative;
}

form p i {
  position: absolute;
  right: 5px;
  top: 5px;
  display: none;
}

form p .fa-check-circle:before {
  color: green;
}

form input:invalid:not(:placeholder-shown)+i {
  display: block;
}

form input:valid:not(:placeholder-shown)+i {
  display: block;
}

#screen-3 form input {
  height: 100px;
}

form input[type="submit"] {
  border: none;
  background-color: #bb9300;
  color: #000;
  text-transform: uppercase;
  font-weight: bold;
  transition: color .15s ease-in-out, background-color .15s ease-in-out, border-color .15s ease-in-out, box-shadow .15s ease-in-out;
}

form input[type="submit"]:hover {
  background-color: #ffc300;
  cursor: pointer;
  -webkit-transition: opacity 300ms ease-out;
  transition: opacity 300ms ease-out;
}
  • Вопрос задан
  • 118 просмотров
Решения вопроса 1
@ligisayan Автор вопроса
Пришел самостоятельно к такому итоговому решению, может быть кому-либо пригодится тоже.
<link href="https://use.fontawesome.com/releases/v5.1.0/css/all.css" rel="stylesheet"/>
<form method="POST" name="f" id="form" action="" onsubmit="return false;">
  <p><input type="text" placeholder="Name" name="name" oninput="InputName(this.value)"><i class="fas fa-check-circle" id="circle-ok-1"></i></p>
  <p><input type="email" placeholder="Email" name="email" oninput="InputEmail(this.value)"><i class="fas fa-check-circle" id="circle-ok-2"></i></p>
  <p><input type="tel" placeholder="Phone" name="phone" oninput="InputPhone(this.value)"><i class="fas fa-check-circle" id="circle-ok-3"></i></p>
  <p><textarea placeholder="Message" name="message" id="form-control" rows="3" oninput="Textarea(this.value)"></textarea><i class="fas fa-check-circle" id="circle-ok-4"></i></p>
  <label id="sending">Sending...</label>
  <input type="submit" value="Send Message" onclick="sendForm(); return false;" />
</form>

function InputName(value) {
  if (value != '') {
    document.getElementById("circle-ok-1").style.display = "block";
  } else {
    document.getElementById("circle-ok-1").style.display = "none";
  }
}

function InputEmail(value) {
  let email = value;
  if (email.length > 0 && (email.match(/.+?\@.+/g) || []).length !== 1) {
    document.getElementById("circle-ok-2").style.display = "none";
  } else {
    document.getElementById("circle-ok-2").style.display = "block";
  }
}

function InputPhone(value) {
  let regExp = /^[+]*[(]{0,1}[0-9]{1,3}[)]{0,1}[-\s\./0-9]*$/g;
  var phone = value.match(regExp);
  if (phone) {
    document.getElementById("circle-ok-3").style.display = "block";
  } else {
    document.getElementById("circle-ok-3").style.display = "none";
  }
}

function Textarea(value) {
  if (value != '') {
    document.getElementById("circle-ok-4").style.display = "block";
  } else {
    document.getElementById("circle-ok-4").style.display = "none";
  }
}

function sendForm() {
  document.getElementById("sending").style.opacity = 1;
}

form {
  width: 1100px;
  max-width: 100%;
}

form input,
form textarea {
  box-sizing: border-box;
  width: 100%;
  background: transparent;
  border: 1px solid #8e908f;
  padding: 10px;
  font-size: 20px;
}

form p {
  position: relative;
}

form p i.fas {
  position: absolute;
  right: 15px;
  top: 15px;
  display: none;
}

form p .fa-check-circle:before {
  color: green;
}

form textarea {
  height: 100px;
}

form input:focus,
form textarea:focus {
  outline-color: #ffc300;
}

form input {
  height: 50px;
}

form input[type="submit"] {
  border: none;
  background-color: #bb9300;
  color: #000;
  text-transform: uppercase;
  font-weight: bold;
  transition: color .15s ease-in-out, background-color .15s ease-in-out, border-color .15s ease-in-out, box-shadow .15s ease-in-out;
}

form input[type="submit"]:hover {
  background-color: #ffc300;
  cursor: pointer;
  -webkit-transition: opacity 300ms ease-out;
  transition: opacity 300ms ease-out;
}

form ::placeholder {
  color: #8e908f;
}

#sending {
  display: block;
  text-align: center;
  padding: 15px;
  font-size: 16px;
  color: #8e908f;
  opacity: 0;
}
Ответ написан
Комментировать
Пригласить эксперта
Ответы на вопрос 1
KorniloFF
@KorniloFF Куратор тега JavaScript
Работаю по font-end / JS
document.getElementById("form").submit(function(event) {
  if (whatever == true) {
    event.preventDefault();
    document.getElementById("submitting").innerHTML = "Submitting...";
  }
});


Меняем на

document.getElementById("form").onsubmit = function(event) {
  if (whatever == true) {
    event.preventDefault();
    document.getElementById("submitting").innerHTML = "Submitting...";
  }
};
Ответ написан
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Войти через центр авторизации
Похожие вопросы