So I have this project I am working on. I was provided with an HTML file that I CAN NOT edit. I have to access the DOM elements strictly with JavaScipt -- no JQuery, just JavaScript. Right now I am working on the validation. So far when you load the page and click submit the first validation works. However, I also want it to loop through the if statement to validate if the user enters a value in the age input field. I've attached my code below. In the end what I want to happen is when a user enters their age they will be able to add it a list, once the submit button is clicked, that I will need to create dynamically. However, if they don't enter an age or enter in a non-numeric number it will display an error. How can I achieve that?
var form = document.getElementsByTagName('form');
form.method = "POST";
form.action = "form-handler";
document.getElementsByTagName('button').onclick = checkAge();
function checkAge() {
var age = document.getElementsByName['age'];
if (age == null || age.value === "") {
alert("Age must be filled out");
return false;
} else {
alert("You entered: " + age.value);
return true;
}
}
.debug {
font-family: monospace;
border: 1px solid black;
padding: 10px;
display: none;
}
<h1>Household builder</h1>
<div class="builder">
<ol class="household"></ol>
<form>
<div>
<label>Age
<input type="text" name="age">
</label>
</div>
<div>
<label>Relationship
<select name="rel">
<option value="">---</option>
<option value="self">Self</option>
<option value="spouse">Spouse</option>
<option value="child">Child</option>
<option value="parent">Parent</option>
<option value="grandparent">Grandparent</option>
<option value="other">Other</option>
</select>
</label>
</div>
<div>
<label>Smoker?
<input type="checkbox" name="smoker">
</label>
</div>
<div>
<button class="add">add</button>
</div>
<div>
<button type="submit" class="GapViewItemselected">submit</button>
</div>
</form>
</div>
<pre class="debug"></pre>
Here's my code pen for it too: