How can I add IF statements displaying alert messages, if the input elements are empty for the following functions in my code hello(), calcAge() and add().
Apologies if parts of the rest of my code is off or incorrect from the page. All my forms and stuff worked, until I started messing with the IF functions, but I left my work as is for you to see.
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>