So I have this piece of HTML and JavaScript
function validate() {
const tabs = document.getElementsByClassName("tab");
const input = tabs[currentTab].querySelectorAll("input[type=tel], input[type=text], input[type=time], input[type=number], input[type=email]");
const radio = tabs[currentTab].querySelectorAll("input[type=radio]");
const select = tabs[currentTab].getElementsByTagName("select");
let valid = true;
if (radio.length == 0) {
for (let i = 0; i < input.length; i++) {
if (input[i].value == "") {
valid = false;
break;
}
}
for (let i = 0; i < select.length; i++) {
if (select[i].value == "") {
valid = false;
break;
}
}
} else if (radio[0].name == "phnum" && radio[0].checked) {
if (input[0].value == "" || input[1].value == "") {
valid = false;
}
} else if (radio[1].name == "phnum" && radio[1].checked) {
if (input[0].value == "" || input[1].value == "" || input[2].value == "") {
valid = false;
}
}
if (valid) {
document.getElementById("next").className = "prevNext";
}
}
<span id="radio">
<label for="phnum1" class="radio-container">
<input type="radio" name="phnum" id="phnum1" value="1" onchange="displayPhone(this);">1 Number
<span class="radio"></span>
</label>
<label for="phnum2" class="radio-container">
<input type="radio" name="phnum" id="phnum2" value="2" onchange="displayPhone(this);">2 Numbers
<span class="radio"></span>
</label>
<label for="phnum3" class="radio-container">
<input type="radio" name="phnum" id="phnum3" value="3" onchange="displayPhone(this);">3 Numbers
<span class="radio"></span>
</label>
</span>
</p><br>
<p id="ph1" class="disable">
<label for="phone-number1">Add a Phone Number: </label><input type="tel" name="phone-number1" id="phone-number1" class="input" placeholder="Add A Phone Number" required oninput="validate();">
</p>
<p id="ph2" class="disable">
<label for="phone-number2">Add a Phone Number: </label><input type="tel" name="phone-number2" id="phone-number2" class="input" placeholder="Add A Phone Number" required onchange="validate();">
</p>
<p id="ph3" class="disable">
<label for="phone-number3">Add a Phone Number: </label><input type="tel" name="phone-number3" id="phone-number3" class="input" placeholder="Add A Phone Number" required onchange="validate();">
</p>
that handles the input added by the user to make a button clickable if all necessary data is added. the problem is when i delete inside the input with back arrow key(the one above enter) the button remains active even if the condition for its activation no longer applies.
thank you guys for your time and help i really do appreciate it. :D
One thing I see - you're setting the class name if valid == true via document.getElementById("next").className = "prevNext";.
But nowhere are you removing that class name if valid == false.
That's probably why you aren't seeing the button disappear when you empty out the fields (if I understand your problem correctly).
if (!valid) { document.getElementById("next").className = ""; } is a quick and dirty way to get what you need.
Related
Learning Javascript and trying to work out the best way to validate a text and number fields on a form.
I have the following html form:
> <form id="captureLegoSets">
<label for="setName">Lego Set Name</label><br>
<input class="input input1" type="text" id="setName" name="setName" value=" ">*<br>
<label for="setTheme">Set Theme</label><br>
<input class="input input1" type="text" id="setTheme" name="setTheme" value=" "><br>
<label for="setReferenceNumber">Reference Number</label><br>
<input class="input input1" type="number" id="setReferenceNumber" name="setReferenceNumber" value="0">*<br>
<label for="setPieceCount">Piece Count</label><br>
<input class="input input1" type="number" id="setPieceCount" name="setPieceCount" value="0">*<br>
<br>
<input class="input input2" type="button" value="Save Set" onclick="captureLegoSets.captureSets()">
<input class="input input2" type="reset" value="Reset Values">
</form>
And attached Javascript (forgive the numerous console.log statements):
this.captureSets = function(){
let setName = " ";
let setTheme = " ";
let setReferenceNumber = 0;
let setPieceCount = 0;
let formFields = document.querySelectorAll(".input1");
console.log(formFields);
for (let i=0; i < formFields.length; i++) {
console.log(formFields[i]);
console.log(formFields[i].id);
console.log(formFields[i].value);
if ((+document.getElementById(formFields[i].id).value) > 0 | (+document.getElementById(formFields[i].id).length) !== null) {
console.log(formFields[i].id + " = " + formFields[i].value);
if(formFields[i].id === "setName"){
setName = +document.getElementById(formFields[i].id).value;
}
if (formFields[i].id === "setTheme") {
setTheme = +document.getElementById(formFields[i].id).value;
}
if (formFields[i].id === "setReferenceNumber") {
setReferenceNumber = +document.getElementById(formFields[i].id).value;
}
if (formFields[i].id === "setPieceCount") {
setPieceCount = +document.getElementById(formFields[i].id).value;
}
console.log(formFields);
} else {
alert("Please add non-zero values to " + formFields[i].id);
}
}
}
The problem I'm experiencing if that the else statement keeps triggering for the text fields if I only check the .value, but if I check the .length, it doesn't trigger at all.
I know I could probably put together a bunch of if statements to check for null, empty and so on, but I'm assuming this would just be poor coding on my part. Is there a better/more concise way of checking for valid inputs?
First you have provided default values to all your text fields, which let the following if check resulting in true, since you have provided default values as " " ( " " is not a null )
if ((document.getElementById(formFields[i].id).value > 0) || (document.getElementById(formFields[i].id).length !== null))
In the above expression you have used !== instead of !=
You used | not || for or operation
Remove + before document ( I don't understand why you have added those. Please explain
Hence,
remove default values / check for right conditions in the conditional statements,
use a p tag to display all the errors in the bottom. I have provided a simple example of concatenating the errors, you can also use an array to collect the errors. In the best case a separate error text right below each text field is awesome.
HTML
<form id="captureLegoSets">
<label for="setName">Lego Set Name</label><br />
<input
class="input input1"
type="text"
id="setName"
name="setName"
/>*<br />
<label for="setTheme">Set Theme</label><br />
<input
class="input input1"
type="text"
id="setTheme"
name="setTheme"
/><br />
<label for="setReferenceNumber">Reference Number</label><br />
<input
class="input input1"
type="number"
id="setReferenceNumber"
name="setReferenceNumber"
/>*<br />
<label for="setPieceCount">Piece Count</label><br />
<input
class="input input1"
type="number"
id="setPieceCount"
name="setPieceCount"
/>*<br />
<br />
<input
class="input input2"
type="button"
value="Save Set"
onclick="captureSets()"
/>
<input class="input input2" type="reset" value="Reset Values" />
</form>
<p id="error-text"></p>
JS
captureSets = function () {
let setName = "";
let setTheme = "";
let setReferenceNumber = 0;
let setPieceCount = 0;
let errorText = "";
let formFields = document.querySelectorAll(".input1");
for (let i = 0; i < formFields.length; i++) {
if (
(document.getElementById(formFields[i].id).value > 0) ||
(document.getElementById(formFields[i].id).length != null)
) {
if (formFields[i].id === "setName") {
setName = document.getElementById(formFields[i].id).value;
}
if (formFields[i].id === "setTheme") {
setTheme = document.getElementById(formFields[i].id).value;
}
if (formFields[i].id === "setReferenceNumber") {
setReferenceNumber = document.getElementById(
formFields[i].id
).value;
}
if (formFields[i].id === "setPieceCount") {
setPieceCount = document.getElementById(formFields[i].id).value;
}
} else {
alert("Please add non-zero values to " + formFields[i].id);
}
}
if (!setName || setName == "") {
errorText += " Fill the name text field <br>";
}
if (!setPieceCount) {
errorText += " Fill the piece count text field <br>";
}
if (!setTheme || setTheme == "") {
errorText += " Fill the theme text field <br>";
}
if (!setReferenceNumber) {
errorText += " Fill the reference number text field <br>";
}
document.getElementById("error-text").innerHTML = errorText;
};
This may or may not help you, but I think, this is easier for you to check this directly by pattern attribute. You just need to put some regex.
An HTML form with an input field that can contain only three letters (no numbers or special characters):
<form>
<label for="country_code">Country code:</label>
<input
type="text" id="country_code" name="country_code"
pattern="[A-Za-z]{3}"
title="Three letter country code">
</form>
https://www.w3schools.com/tags/att_input_pattern.asp
I tried to build a validation form using JavaScript which handles these errors:
The Name field should not be empty
The phone number field can contain only numbers (exactly 10 numbers)
One option should be selected (radio)
At least one car from checkboxes is selected and at max 3 cars
But the problem with my code is it has not worked in all cases. I mean if I selected submit it shows me the error message just in the name field, not on other fields.
For example here -
here my HTML code
<body>
<div class="MainBackground">
<h1 id="title">Car Company</h1>
</div>
<div class="cars">
<form method="POST" name="form-car" id="form-car">
<p id="decription"> users' request</p>
<div id="name_div">
<label id="lable-name" for="name">Name: </label>
<input id="name" type="text" name="yourName" placeholder="Enter your name"> <br>
<span id="errorname"></span>
</div>
<br> <br>
<label id="lable-Phone" for="Phone">Phone:</label>
<input id="phone" type="text" name="phonefild" placeholder="Enter your Phone Number"> <br>
<span id="errorpass"></span>
<br> <br>
<label id="lable-age" for="Age">Age:</label>
<br>
<input type="radio" name="group1" value="T"> 18-25
<br>
<input type="radio" name="group1" value="A"> 26-35
<br>
<input type="radio" name="group1" value="O"> 35-55
<br>
<input type="radio" name="group1" value="AO"> 36-80
<br>
<input type="radio" name="group1" value="VO"> 80-95
<br>
<span id="radioerorr"></span>
<br> <br>
<label for="check">Choice cars to tested</label>
<br>
<input class="checkbox" type="checkbox" id="option1" name="car1" value="BMW">
<label for="vehicle1">BMW</label><br>
<input class="checkbox" type="checkbox" id="option2" name="car2" value="Ferrari">
<label for="vehicle2">Ferrari</label><br>
<input checkbox="checkbox" type="checkbox" id="option3" name="car3" value="Ford">
<label for="vehicle3">Ford</label><br>
<input class="checkbox" type="checkbox" id="option4" name="car4" value="Audi">
<label for="vehicle4">Audi</label><br>
<input class="checkbox" type="checkbox" id="option5" name="car5" value="Cadillac">
<label for="vehicle5">Cadillac</label><br>
<span id="checkboxerorr"></span>
<br> <br>
<div class="center">
<button onclick="return validition()" id="submit" type="submit" name="button">submit</button>
<button id="reset" type="reset" name="button">reset</button>
</div>
</form>
</div>
And here my javascript code
function validition() {
var phoneinpute = document.getElementById('phone').value;
var radios = document.getElementsByTagName('input');
var value;
var inputs = document.getElementsByTagName("input");
var count1 = 0;
var count2 = 0;
var regex = /(5|0)([0-9]{8})$/;
if (document.getElementById('name').value == "") {
document.getElementById('errorname').innerHTML = "name should not be empty";
document.getElementById('name').style.borderColor = "red";
return false;
} else if (document.getElementById('name').value != "") {
document.getElementById('errorname').innerHTML = "";
document.getElementById('name').style.borderColor = "green";
}
if (regex.test(phoneinpute)) {
document.getElementById('errorpass').innerHTML = "";
document.getElementById('phone').style.borderColor = "green";
//return true;
} else {
document.getElementById('errorpass').innerHTML = "Invalide phone number";
document.getElementById('phone').style.borderColor = "red";
return false;
}
for (var i = 0; i < radios.length; i++) {
if (radios[i].type == "radio" && radios[i].checked) {
count1++;
}
if (count1 == 1) {
document.getElementById('radioerorr').innerHTML = "";
break;
} else {
document.getElementById('radioerorr').innerHTML = "one option should be selected";
return false
}
}
for (var i = 0; i < inputs.length; i++) {
if (inputs[i].type == "checkbox" && inputs[i].checked) {
count2++;
}
if (count2 > 3 || count2 == 0) {
document.getElementById('checkboxerorr').innerHTML = "please choose at least one car and at most 3 cars";
return false
} else {
document.getElementById('checkboxerorr').innerHTML = "";
}
}
You are using return statements in your validations, if you return from your 1st validation (name box), the other code blocks will not execute. Use a local boolean to determine your return type and return that at the end of your function, that way, all of your validation code runs. Also, your radio button and checkbox validation logic is flawed, you set an error message on each iteration of the loop if count1 or count2 doesn't meet your conditions. Change it to something like the following:
function validition() {
let valid = true; //local boolean to return at the end of your function
var phoneinpute = document.getElementById('phone').value;
var radios = document.getElementsByTagName('input');
var value;
var inputs = document.getElementsByTagName("input");
var count1 = 0;
var count2 = 0;
var regex = /(5|0)([0-9]{8})$/;
//Name validation
if (document.getElementById('name').value == "") {
document.getElementById('errorname').innerHTML = "name should not be empty";
document.getElementById('name').style.borderColor = "red";
valid = false;
} else if (document.getElementById('name').value != "") {
document.getElementById('errorname').innerHTML = "";
document.getElementById('name').style.borderColor = "green";
}
//Phone number validation
if (regex.test(phoneinpute)) {
document.getElementById('errorpass').innerHTML = "";
document.getElementById('phone').style.borderColor = "green";
} else {
document.getElementById('errorpass').innerHTML = "Invalide phone number";
document.getElementById('phone').style.borderColor = "red";
valid = false;
}
//Radio button validation
for (var i = 0; i < radios.length; i++) {
if (radios[i].type == "radio" && radios[i].checked) {
count1++;
}
if (count1 == 1) {
document.getElementById('radioerorr').innerHTML = "";
break;
}
}
//check to see if you had a checked radio button, if not, add error
//and mark local boolean as false
if(count1 < 1){
document.getElementById('radioerorr').innerHTML = "one option should be selected";
valid = false;
}
//Checkbox validation
for (var i = 0; i < inputs.length; i++) {
if (inputs[i].type == "checkbox" && inputs[i].checked) {
count2++;
}
}
//Do your checkbox validation after the for loop
if (count2 > 3 || count2 == 0) {
document.getElementById('checkboxerorr').innerHTML = "please choose at least one car and at most 3 cars";
valid = false;
} else {
document.getElementById('checkboxerorr').innerHTML = "";
}
//return your local boolean value
return valid;
}
I need to add a message box and e-mail textbox and display everything in my form in the 'msgresults' tag.
I need to add a Message box and and e-mail text box. Then I need all information to be shown within the MsgResults tag. The radioboxes already are shown this way.
function validateForm(){
var name = document.getElementById("name").value;
var age = document.getElementById("age").value;
if (name == "" || name == null){
resultsMsg("We need your name please");
}else{
if(age == "" || name == null || isNaN(age)){
resultsMsg("Please enter a number for your age");
}else{
if(!getSkill()){
resultsMsg("Please select the type of problem you are having.");
}else{
resultsMsg("Type of Problem: " + getSkill());
}//end else
}// end function
}
}
function getSkill(){
var isChecked = false;
var theSelection;
var skills = document.getElementsByName('skillset');
for (var i=0; i < skills.length; i++){
if(skills[i].checked){
isChecked = true;
theSelection = skills[i].value;
break;
}
}
if(isChecked){
return theSelection;
}else{
return false;
} // end else
} // end function
function resultsMsg(s){
var resultsBox = document.getElementById("results");
resultsBox.innerHTML=s;
} // end function
<form name="form1" id="form1" action="" method="post">
<label>Full Name:
<input type="text" id="name" name="name">
</label>
<br> <!-- new line here -->
<label>Your Age:
<input type="text" id="age" name="age">
</label>
<br> <!-- new line here -->
<input type="radio" name="skillset" value="Technical Issues">Technical Issues</br>
<input type="radio" name="skillset" value="Recovery Issues">Recovery Issues</br>
<input type="radio" name="skillset" value="Hardware Issues">Hardware Issues</br>
<input type="radio" name="skillset" value="Software Issues">Software Issues</br>
<input type="radio" name="skillset" value="Software Crashes">Software Crashes</br>
<input type="radio" name="skillset" value="Hardware Malfunctions">Hardware Malfunctions</br>
<input type="radio" name="skillset" value="General Problems">General Problems</br>
<input type="button" value="Submit" onClick="validateForm();"> <input type="reset" value="Clear Form">
</form>
<div id="results"></div>
If I understand your goal correctly, you want to add the given name and age to the result-div, on top of the 'Type of Problem' that is already show. That can be easily achieved by adding the correct variables to the last else-loop in your validateForm function. Something among the following should probably work:
resultsMsg("Name: "+name+ "<br>Age: " +age+ "<br>Type of Problem: " + getSkill());
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
How to print error message under respective input field if left empty and error message must be removed when filled, how to proceed further i have not used javascript for validation earlier.
script code
function validateForm() {
var a = document.forms["student_reg"]["name"].value;
if (a == null || a == "") {
alert("Name must be filled out");
return false;
}
var b = document.forms["student_reg"]["email"].value;
if (b == null || b == "") {
alert("Email must be filled out");
return false;
}
var c = document.forms["student_reg"]["username"].value;
if (c == null || c == "") {
alert("Username must be filled out");
return false;
}
var d = document.forms["student_reg"]["password"].value;
if (d == null || d == "") {
alert("Password must be filled out");
return false;
}
var e = document.forms["student_reg"]["roll_no"].value;
if (e == null || e == "") {
alert("Roll no must be filled out");
return false;
}
}
html code is here
<body>
Login
<form name="student_reg" method="POST" action="" onsubmit="return validateForm()">
<p>NAME:</p>
<input type="text" name="name" value="" >
<span class="error"><p id="name_error"></p></span>
<p>EMAIL:</p>
<input type="text" name="email" value="" >
<span class="error"><p id="email_error"></p></span>
<p>USERNAME:</p>
<input type="text" name="username" value="" >
<span class="error"><p id="username_error"></p></span>
<p>PASSWORD:</p>
<input type="password" name="password" value="" >
<span class="error"><p id="password_error"></p></span>
<p>ROLL NO:</p>
<input type="number" name="roll_no" value="" >
<span class="error"><p id="roll_no_error"></p></span>
<br/>
<br/>
<br/>
<input type="submit" name="submit" value="submit">
</form>
</body>
You can try this code:
It will check errors and returns at last after displaying all error messages if any.
function validateForm() {
var error = 0;
var a = document.forms["student_reg"]["name"].value;
document.getElementById('name_error').innerHTML = '';
if (a == null || a == "") {
// alert("Name must be filled out");
error++;
document.getElementById('name_error').innerHTML = 'Name must be filled out';
}
var b = document.forms["student_reg"]["email"].value;
document.getElementById('email_error').innerHTML = '';
if (b == null || b == "") {
// alert("Email must be filled out");
error++;
document.getElementById('email_error').innerHTML = 'Email must be filled out';
}
var c = document.forms["student_reg"]["username"].value;
document.getElementById('username_error').innerHTML = '';
if (c == null || c == "") {
// alert("Username must be filled out");
error++;
document.getElementById('username_error').innerHTML = 'Username must be filled out';
}
var d = document.forms["student_reg"]["password"].value;
document.getElementById('password_error').innerHTML = '';
if (d == null || d == "") {
// alert("Password must be filled out");
error++;
document.getElementById('password_error').innerHTML = 'Password must be filled out';
}
var e = document.forms["student_reg"]["roll_no"].value;
document.getElementById('roll_no_error').innerHTML = '';
if (e == null || e == "") {
// alert("Roll no must be filled out");
error++;
document.getElementById('roll_no_error').innerHTML = 'Roll no must be filled out';
}
if(error>0) {
return false;
}
return true;
}
Keep all the name attributes in array and validate in loop. As your ID is related to name attribute, concatenate the name with _error to get the ID of the error placeholder.
function validateForm() {
var names = ['name', 'email', 'username', 'password', 'roll_no'];
var errorCount = 0;
names.forEach(function(el) {
var val = document.forms["student_reg"][el].value;
if (val == null || val == "") {
document.getElementById(el + '_error').textContent = el.toUpperCase().replace('_', ' ') + " must be filled out";
++errorCount;
}
});
if (errorCount) return false;
}
<form name="student_reg" method="POST" action="" onsubmit="return validateForm()">
<p>NAME:</p>
<input type="text" name="name" value="">
<span class="error"><p id="name_error"></p></span>
<p>EMAIL:</p>
<input type="text" name="email" value="">
<span class="error"><p id="email_error"></p></span>
<p>USERNAME:</p>
<input type="text" name="username" value="">
<span class="error"><p id="username_error"></p></span>
<p>PASSWORD:</p>
<input type="password" name="password" value="">
<span class="error"><p id="password_error"></p></span>
<p>ROLL NO:</p>
<input type="number" name="roll_no" value="">
<span class="error"><p id="roll_no_error"></p></span>
<br/>
<br/>
<br/>
<input type="submit" name="submit" value="submit">
</form>
You can iterate through all elements of the form student_reg to validate email and required and print error message under respective input field if no value was set:
const validateForm = () => {
const form = document.forms['student_reg'],
inputs = [...form.getElementsByTagName('input')],
errors = [...form.getElementsByClassName('error')],
regex = /\S+#\S+\.\S+/,
setErrorMsg = (str, msg) => `${str.replace('_', ' ')} ${msg}`
let countErrors = 0
inputs.forEach((input, index) => {
// clear all errors
(errors[index] || '').innerHTML = ''
// validate email
if (input.name === 'email' && !regex.test(input.value)) {
errors[index].innerText = setErrorMsg(input.name, 'should be valid')
countErrors++
}
// validate required
if (!input.value) {
errors[index].innerText = setErrorMsg(input.name, 'field is required')
countErrors++
}
})
return countErrors === 0
}
p {
font-size: 13px;
margin: 4px 0 0;
}
.error {
font-size: 12px;
padding: 6px 0 4px;
color: red;
display: block
}
.error:first-letter {
text-transform: uppercase
}
button {
margin-top: 8px;
font-size: 16px;
}
<form name="student_reg" method="POST" action="" onsubmit="return validateForm()">
<p>NAME:</p>
<input type="text" name="name" value="">
<span class="error"></span>
<p>EMAIL:</p>
<input type="text" name="email" value="">
<span class="error"></span>
<p>USERNAME:</p>
<input type="text" name="username" value="">
<span class="error"></span>
<p>PASSWORD:</p>
<input type="password" name="password" value="">
<span class="error"></span>
<p>ROLL NO:</p>
<input type="number" name="roll_no" value="">
<span class="error"></span>
<button>Submit</button>
</form>
simple form It hold the Span for the Error msg.The span Id is very important here.you need to make color for errors using css
<form id="loginform" name="loginform" action="" method="post">
<label>Name</label>
<input type="text" name="username" />
<p></p>
<span id="usernameError"></span>
<p></p>
<label>Pwd</label>
<input type="password" name="password" />
<p></p>
<span id="passwordError"></span>
<p></p>
<input type="submit" value="Submit" />
</form>
script
<script type="application/javascript">
window.onload = function(){
function handleinput(){
if(document.loginform.username.value == ""){
document.getElementById("usernameError").innerHTML = "You must enter a username";
return false;
}
if(document.loginform.password.value == ""){
document.getElementById("passwordError").innerHTML = "You must enter a password";
return false;
}
}
document.getElementById("loginform").onsubmit = handleinput;
}
</script>
I've been working on this assignment for the longest while. My form validations weren't working previously but then I found out what the error was & everything was working perfectly.
Later on, I had made some changes to the code then deleted those changes and now the validations aren't working again & I can't seem to find what the problem is this time.
Below is my unfinished code:
function validateEmail() {
var email = document.getElementById('email').value;
if( email==null || email=="")
{
alert("Please input an email address");
}
}
function validateFName() {
var firstname = document.getElementById('firstname').value;
if( firstname==null || firstname=="")
{
alert("Please input a last name");
return false;
}
}
function validateLName() {
var lastname = document.getElementById('lastname').value;
if( lastname==null || lastname=="")
{
alert("Please input a last name");
}
}
function validateGender() {
var gender = document.getElementById('gender').value;
if( gender==null || gender=="")
{
alert("Please select a gender");
}
}
function validateDate() {
var date = document.getElementById('date').value;
if( date==null || date=="")
{
alert("Please select a date");
}
}
function validateVName() {
var vname = document.getElementById('vname').value;
if( vname==null || vname=="")
{
alert("Please input a victim's name");
}
}
function validateVEmail() {
var vemail = document.getElementById('vemail').value;
if( vemail==null || vemail=="")
{
alert("Please input a victim's email");
}
}
<div id="navi">
<nav>
<ul class="fancyNav">
<li id="home">Home</li>
<li id="news">TRUTH</li>
<li id="about">DARE</li>
</ul>
</nav>
</div>
<div id="box">
<form id="truth">
<h1> Truth </h1>
<label> First Name: </label> <input type="text" name="firstname" id="firstname" maxlength="30" placeholder="John" /> <br><br>
<label> Last Name: </label> <input type="text" name="lastname" id="lastname" maxlength="30" placeholder="Doe" /> <br><br>
<label> Email:</label> <input type="text" name="email" id="email" /> <br><br>
<label> Male </label><input type="radio" name="gender" id="gender" value="male"/>
<label> Female </label><input type="radio" name="gender" id="gender" value="female"/> <br><br>
<label> Date to be performed: </label><input type="date" name="date" id="date" /><br><br>
<h2> Victim </h2>
<label> Name: </label> <input type="text" name="vname" id="vname" maxlength="30" /><br><br>
<label> Email:</label> <input type="text" name="vemail" id="vemail" /> <br><br>
<h2> Please select a truth questions below </h2> <br>
<input type="radio" name="truth" value="q1"> Have you ever fallen and landed on your head? <br>
<input type="radio" name="truth" value="q2"> Have you ever return too much change? <br>
<input type="radio" name="truth" value="q3"> Have you ever been admitted into the hospital? <br>
<input type="radio" name="truth" value="q4"> Have you ever baked a cake? <br>
<input type="radio" name="truth" value="q5"> Have you ever cheated on test? <br>
<input type="radio" name="truth" value="q6"> Did you ever wish you were never born? <br>
<input type="radio" name="truth" value="q7"> Did you ever hide from Sunday School? <br><br>
<input type="submit" onclick="validateFName(); validateLName(); validateGender(); validateDate(); validateVName(); validateVEmail();" /> <br>
</form>
</div>
<input type="submit" onclick="validateFName(); validateLName(); validateGender(); v
typo in function name, onclick="validateFName()...
it should be validateLName()
and you define duplicate
<!DOCTYPE html>
<html> // remove this one
The best possible solution would be to not use any alert boxes at all but instead embed the error message next to the place of the error, but that would be more involved. Instead, to stick with this solution, first add an id to your submit button:
<button type="submit" id="truth-submit">Submit</button>
Then, attach an onclick handler through JavaScript (and rewrite your code to be more re-usable):
// Only run when the window fully loads
window.addEventListener("load", function() {
function validateEmail() {
var email = document.getElementById("email").value;
if (email === null || email === "") {
return "Please input an email address";
}
return "";
}
function validateFName() {
var firstname = document.getElementById("firstname").value;
if (firstname === null || firstname === "") {
return "Please input an first name";
}
return "";
}
function validateLName() {
var lastname = document.getElementById("lastname").value;
if (lastname === null || lastname === "") {
return "Please input an last name";
}
return "";
}
function validateGender() {
var gender = document.getElementById("gender").value;
if (gender === null || gender === "") {
return "Please select a gender";
}
return "";
}
function validateDate() {
var date = document.getElementById("date").value;
if (date === null || date === "") {
return "Please select a date";
}
return "";
}
function validateVName() {
var vname = document.getElementById("vname").value;
if (vname === null || vname === "") {
return "Please input a victim's name";
}
return "";
}
function validateVEmail() {
var vemail = document.getElementById("vemail").value;
if (vemail === null || vemail === "") {
return "Please input a victim's email";
}
return "";
}
document.getElementById("truth-submit").addEventListener("click", function(event) {
// Grab all of the validation messages
var validationMessages = [validateFName(), validateLName(),
validateGender(), validateDate(), validateVName(), validateVEmail()];
var error = false;
// Print out the non-blank ones
validationMessages.forEach(function(message) {
if (message) {
alert(message);
error = true;
}
});
// Stop submission of the form if an error occurred
if (error) {
event.preventDefault();
}
}, false);
}, false);