javascript表单验证和禁用提交

lnlaulya  于 2021-09-13  发布在  Java
关注(0)|答案(0)|浏览(149)

我正在尝试表单验证。我有一个功能,可以在用户未输入表单字段时发出警报,但我正试图找到一种方法,在所有输入字段未填充时禁用“提交”按钮,以及一个事件侦听器,在成功提交时向用户发出警报。
我真的很感谢你的帮助!

function validateForm() {
  var canSubmit = true;
  var name = document.forms['myForm']["name"].value;
  if (name == "") {
    alert("Name must be filled out");
    canSubmit = false;
  }
  var address = document.forms["myForm"]["address"].value;
  if (address == "") {
    alert("Address must be filled out");
    canSubmit = false;
  }
  var city = document.forms["myForm"]["city"].value;
  if (city == "") {
    alert("City must be filled out");
    canSubmit = false;
  }
  var state = document.forms["myForm"]["state"].value;
  if (state == "") {
    alert("State must be filled out");
    return false;
  }
  var zip = document.forms["myForm"]["zip"].value;
  if (zip == "") {
    alert("Zip code must be filled out");
    canSubmit = false;
  }
  e.preventDefault();
}

//trying to work on submit button disabled until all form elements are filled
function checkform() {
  var f = document.forms["form"].elements;
  var cansubmit = true;

  for (var i = 0; i < f.length; i++) {
    if (f[i].value.length == 0) cansubmit = false;
  }

  if (cansubmit) {
    document.getElementById('submit').disabled = false;
  } else {
    document.getElementById('submit').disabled = 'disabled';
  }
}

var form = document.getElementById('#form');
form.addEventListener('submit', function(e) {
  if (validateForm() == true) {
    alert("Submitted");
  } else {
    canSubmit = false;
  }
  e.preventDefault;
});
<h1 class="text-center">Lesson 10 Project</h1>
<form class="form" name="myForm" id="myForm" action="">
  First Name:
  <input type="text" name="name" id="name" placeholder="First Name" onkeydown="return checkform()" />
  <br /> Address:
  <input type="text" name="address" id="address" placeholder="Address" onkeyup="checkform()" />
  <br /> City:
  <input type="text" name="city" id="city" placeholder="City" onkeyup="checkform()" />
  <br /> State
  <input type="text" name="state" id="state" placeholder="State" onkeyup="checkform()" />
  <br /> Zip Code:
  <input type="text" name="zip" id="zip" placeholder="Zip Code" onkeyup="checkform()" />
  <br />
  <input type="submit" id="submit" onclick="validateForm()" />
</form>

https://codepen.io/jbeezy3/pen/yzvgelo

暂无答案!

目前还没有任何答案,快来回答吧!

相关问题