添加IF语句以从表单执行验证

时间:2018-03-22 22:13:02

标签: javascript arrays forms function if-statement

如果我的代码hello()calcAge()add()中的以下函数的输入元素为空,如何添加显示警报消息的IF语句。

如果我的其他部分代码在页面中关闭或不正确,请致歉。我的所有表格和内容都有效,直到我开始搞乱IF功能,但我离开了我的工作,你可以看到。

function hello() {
  var name = document.getElementById("name").value;
  var yob = document.getElementById("yob").value;
  document.getElementById("pForm").innerHTML = "Hello " + name + " you were born in " + yob;
}

function calcAge() {
  var yob = document.getElementById("yob").value;
  var date = new Date();
  var year = date.getFullYear();
  var age = year - yob;
  var alreadyOutput = document.getElementById("pForm").innerHTML;
  document.getElementById("pForm").innerHTML = alreadyOutput + " you are " + age;
}
var itemArray = [];

function add() {
  var item = document.getElementById('item');
  itemArray.push(item.value);
  item.value = "";
  item.focus();
}

function showList() {
  document.getElementById('pList').innerHTML = itemArray;
}

function clearList() {
  document.getElementById('pList').innerHTML = itemArray = [];
}
if (name = "") {
  alert("Please enter your name and date of birth");
  document.getElementById("name").innerHTML = name;
  hello = false;
}

if (yob = "") {
  alert("Please enter your date of birth");
  document.getElementById("yob").innerHTML = name;
  calcAge = false;
}

if (item = "") {
  alert("Please enter your date of item");
  document.getElementById("item").innerHTML = name;
  add = false;
}
form {
  width: 500px;
  margin: 0px auto;
  border: 1px solid khaki;
  background-color: antiquewhite;
  border-collapse: collapse;
  padding: 10px;
  margin-bottom: 20px;
}

form h2 {
  margin: 0;
}

input {
  margin: 5px;
}
<h1>Practice Manipulating Forms #1</h1>

<form id='calcForm'>
  <h2>Calc Form</h2>
  <span>Name:</span>
  <input type='text' name='name' id='name'><br>
  <span>Year of Birth:</span>
  <input type='text' name='yob' id='yob'><br>

  <input type='button' name='btnCalc' id='btnHello' value='Hello' onclick='hello()'>
  <input type='button' name='btnCalc' id='btnCalc' value='Calc Age' onclick='calcAge()'>

  <p id='pForm'></p>
</form>

<form id='listForm'>
  <h2>List Form</h2>

  <span>Item:</span>
  <input type='text' name='item' id='item'><br>

  <input type='button' name='btnAdd' id='btnAdd' value='Add to List' onclick='add()'>
  <input type='button' name='btnClear' id='btnClear' value='Clear List' onclick='clearList()'>
  <input type='button' name='btnShow' id='btnShow' value='Show List' onclick='showList()'>

  <p id='pList'></p>
</form>

0 个答案:

没有答案