Radio Buttons with JavaScript in a Form - javascript

I have this JavaScript code that I am using for form validation and I am trying to put two radio buttons into and have them validate the same way that the rest of the form is but am not getting it to work. My html for the buttons is:
<label class="required" for="buttons">How May I Contact You:</label><br/>
<input id="radio" type="radio0" name="contact" value="email">Email<br>
<input id="radio" type="radio1" name="contact" value="no contact">No Contact<br>
<span id="radio_validation" class="error"></span>
<input type="submit" value="Send email" onclick="validate()" value="Check"/>
This is the JavaScript that I am using. Any help would be greatly appreciated. I do not know much about JavaScript yet.
function validateForm() {
var valid = 1;
var email = document.getElementById('email');
var email_validation = document.getElementById("email_validation");
var name = document.getElementById('name');
var name_validation = document.getElementById("name_validation");
var message_validation = document.getElementById("message_validation");
var filter = /^([a-zA-Z0-9_\.\-])+\#(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
if (name.value === "") {
valid = 0;
name_validation.innerHTML = "Field Required";
name_validation.style.display = "block";
name_validation.parentNode.style.backgroundColor = "#FFDFDF";
} else {
name_validation.style.display = "none";
name_validation.parentNode.style.backgroundColor = "transparent";
}
if (message.value === "") {
valid = 0;
message_validation.innerHTML = "Field Required";
message_validation.style.display = "block";
message_validation.parentNode.style.backgroundColor = "#FFDFDF";
} else {
message_validation.style.display = "none";
message_validation.parentNode.style.backgroundColor = "transparent";
}
if (email.value === "") {
valid = 0;
email_validation.innerHTML = "Field Required";
email_validation.style.display = "block";
email_validation.parentNode.style.backgroundColor = "#FFDFDF";
} else {
email_validation.style.display = "none";
email_validation.parentNode.style.backgroundColor = "transparent";
}
if(!filter.test(email.value)) {
valid = 0;
email_validation.innerHTML = "Invalid email address";
email_validation.style.display = "block";
email_validation.parentNode.style.backgroundColor = "#FFDFDF";
} else {
email_validation.style.display = "none";
email_validation.parentNode.style.backgroundColor = "transparent";
}
if (!valid)
return false;
}

Related

How can I remove the specific error message after regex validation is done?

The regex validation works but the error messages which have been displayed persist till the form is submitted. How can this be corrected so that after each attempt(Once the submit button is clicked) the input that has been validated will have the corresponding error message not displayed? *The attempt to implement this part is the last 2 else if statements, they also make the validation work partially. Take them out and the validation works but the error message issues persist.
document.addEventListener('DOMContentLoaded', () => {
document.querySelector('#sbutton').addEventListener('click', function(event) {
event.preventDefault();
let phoneInput = document.querySelector('#phone').value;
let phoneRegex = /^(0|\+234)[789]{0,1}([0-1]{1})([0-9]{8})$/;
const phoneError = document.querySelector('#phoneErr');
let inputV = document.querySelector('#budget').value;
const errorMessage = document.querySelector('#errormsg');
let form = document.querySelector("form");
if (phoneInput == "" || !phoneRegex.test(phoneInput)) {
phoneError.innerHTML = "Please enter a valid phone number";
phoneError.style.display = "block";
} else if (inputV == "" || inputV < 300000) {
errorMessage.innerHTML = "Enter at least 300000"
errorMessage.style.display = "block";
} else if (phoneRegex.test(phoneInput)) {
phoneError.innerHTML = "";
phoneError.style.display = "none";
return;
} else if (inputV >= 300000) {
errorMessage.innerHTML = ""
errorMessage.style.display = "none";
return;
} else {
phoneError.innerHTML = "";
phoneError.style.display = "none";
errorMessage.innerHTML = ""
errorMessage.style.display = "none";
form.submit();
}
})
})
<form action="https://dragonmm.com" method="post">
<div class="contact-box">
<div class="left1"></div>
<div class="right1">
<h2>Start</h2>
<label for="name"></label>
<input id="name" type="text" class="field" placeholder="Name" required>
<label for="email"></label>
<input id="email" type="text" class="field" placeholder="Email" required>
<label for="phone"></label>
<input id="phone" type="text" class="field" placeholder="Phone" required>
<div id="phoneErr"></div>
<label for="budget"></label>
<input id="budget" type="text" name="budget" class="field budgetInput" placeholder="Budget" required>
<div id="errormsg"></div>
<button type="submit" value="Send" class="btn1" id="sbutton">Send</button>
</div>
</div>
</form>
Acutally, your regex method is not working properly in my system so I changed with my regex method. if phoneInput variable will generate any error then it will display this message "Please enter a valid phone number" and return from there. if number format will be correct than it will empty the phoneError. Take a look at this code.
document.addEventListener('DOMContentLoaded', () => {
document.querySelector('#sbutton').addEventListener('click', function(event) {
event.preventDefault();
let phoneInput = document.querySelector('#phone').value;
let phoneRegex = /^(0|\+234)[789]?[0-9]{10}$/;
const phoneError = document.querySelector('#phoneErr');
let inputV = document.querySelector('#budget').value;
const errorMessage = document.querySelector('#errormsg');
let form = document.querySelector("form");
if (phoneInput == "" || !phoneRegex.test(phoneInput)) {
phoneError.innerHTML = "Please enter a valid phone number";
return;
} else {
phoneError.innerHTML = "";
}
if (inputV == "" || inputV < 300000) {
errorMessage.innerHTML = "Enter at least 300000";
return;
} else {
errorMessage.innerHTML = "";
form.submit();
}
})
})

Turn boolean to false in order to stop event.preventDefault

I have a form where the user needs to write their first name, last name, email address, and phone number. The user has to be based in the UK for this to work.
I have no problem preventing the form to be submitted if the inputs are blank or the format is not correct, however, I cannot submit the form successfully once all the input values are correct.
I know it has something to do with my stopSubmit code, but I can't seem to turn true into false once all the input values are correct.
Here is my Javascript code:
window.onload = function () {
let theForm = document.getElementById("form");
theForm.addEventListener("submit", function (event) {
let stopSubmit = false;
for (let i = 0; i < theForm.elements.length; i++) {
cleanUpErrors();
if (!checkFirstName(theForm.elements[0])) {
theForm.elements[i].style.borderColor = "#990000";
stopSubmit = true;
}
if (!checkLastName(theForm.elements[1])) {
theForm.elements[i].style.borderColor = "#990000";
stopSubmit = true;
}
if (!checkEmail(theForm.elements[2])) {
theForm.elements[i].style.borderColor = "#990000";
stopSubmit = true;
}
if (!checkPhone(theForm)) {
theForm.elements[i].style.borderColor = "#990000";
stopSubmit = true;
}
}
if (stopSubmit) {
event.preventDefault();
}
}, false)
}
function checkFirstName(input) {
let elemPos = document.getElementById("firstName");
let inputValue = input.value;
let errorMessage = "";
if (inputValue === null || inputValue === "") {
errorMessage = "This field is empty.";
}
if (inputValue !== "") {
if (inputValue.length < 3) {
errorMessage = "This field has less than 3 characters.";
}
}
renderErrorMessage(elemPos, errorMessage);
}
function checkLastName(input) {
let elemPos = document.getElementById("lastName");
let inputValue = input.value;
let errorMessage = "";
if (inputValue === null || inputValue === "") {
errorMessage = "This field is empty.";
}
if (inputValue !== "") {
if (inputValue.length < 3) {
errorMessage = "This field has less than 3 characters.";
}
}
renderErrorMessage(elemPos, errorMessage);
}
function checkEmail(input) {
let elemPos = document.getElementById("email");
let emailValue = input.value;
let errorMessage = "";
let regex = /^(([^<>()\[\]\\.,;:\s#"]+(\.[^<>()\[\]\\.,;:\s#"]+)*)|(".+"))#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
if (!emailValue.match(regex)) {
errorMessage = "Not a valid email address.";
}
if (emailValue === "") {
errorMessage = "This field is empty.";
}
renderErrorMessage(elemPos, errorMessage);
}
function checkPhone(input) {
let elemPos = input.phone;
let phoneValue = input.phone.value;
let errorMessage = "";
let regex = /^(((\+44\s?\d{4}|\(?0\d{4}\)?)\s?\d{3}\s?\d{3})|((\+44\s?\d{3}|\(?0\d{3}\)?)\s?\d{3}\s?\d{4})|((\+44\s?\d{2}|\(?0\d{2}\)?)\s?\d{4}\s?\d{4}))(\s?\#(\d{4}|\d{3}))?$/;
if (!phoneValue.match(regex)) {
errorMessage = "Not a valid UK phone number.";
}
if (phoneValue === "") {
errorMessage = "This field is empty.";
}
renderErrorMessage(elemPos, errorMessage);
}
function renderErrorMessage(selectedElem, errorMessage) {
let errorElem = document.createElement("span");
errorElem.setAttribute("class", "error");
let errorText = document.createTextNode(errorMessage);
errorElem.appendChild(errorText);
selectedElem.parentNode.insertBefore(errorElem, selectedElem.nextSibling);
return selectedElem;
}
function cleanUpErrors() {
let indicator = document.getElementsByTagName("span");
for (let i = 0; i < indicator.length; i++) {
indicator[i].setAttribute("class", "hide");
}
}
Here is my HTML code:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Personal Information Form</title>
<script src="scripts/test5.js"></script>
<link rel="stylesheet" href="css/test.css">
</head>
<body>
<form id="form" action="test3success.html" novalidate="novalidate">
<label for="firstName">First Name (required)</label>
<input id="firstName" type="text" name="text" required>
<label for="lastName">Last Name (required)</label>
<input id="lastName" type="text" name="text" required>
<label for="email">Email (required)</label>
<input id="email" type="email" required>
<label for="phone">Phone Number (required)</label>
<input id="phone" type="tel" required>
<button type="submit">Submit</button>
</form>
</body>
</html>
Your checks need to return true or false considering you are evaluating these within if statements.
So, when you are doing
if (!checkFirstName(theForm.elements[0])) {
This evaluates to
if (!undefined) {
Since checkFirstName (and the others) return nothing (undefined), which means stopSubmit is always set to true
Note: There are cleaner ways to do this, I just did a check for errorMessage being blank.
Also as pointed out in the comments, you are passing the entire form to the checkPhone function, when you could just pass the input as you are doing with the other checks.
window.onload = function () {
let theForm = document.getElementById("form");
theForm.addEventListener("submit", function (event) {
let stopSubmit = false;
for (let i = 0; i < theForm.elements.length; i++) {
cleanUpErrors();
if (!checkFirstName(theForm.elements[0])) {
theForm.elements[i].style.borderColor = "#990000";
stopSubmit = true;
}
if (!checkLastName(theForm.elements[1])) {
theForm.elements[i].style.borderColor = "#990000";
stopSubmit = true;
}
if (!checkEmail(theForm.elements[2])) {
theForm.elements[i].style.borderColor = "#990000";
stopSubmit = true;
}
if (!checkPhone(theForm)) {
theForm.elements[i].style.borderColor = "#990000";
stopSubmit = true;
}
}
if (stopSubmit) {
event.preventDefault();
console.log('default prevented')
}
}, false)
}
function checkFirstName(input) {
let elemPos = document.getElementById("firstName");
let inputValue = input.value;
let errorMessage = "";
if (inputValue === null || inputValue === "") {
errorMessage = "This field is empty.";
}
if (inputValue !== "") {
if (inputValue.length < 3) {
errorMessage = "This field has less than 3 characters.";
}
}
renderErrorMessage(elemPos, errorMessage);
if (errorMessage !== "") {
return false
}
return true
}
function checkLastName(input) {
let elemPos = document.getElementById("lastName");
let inputValue = input.value;
let errorMessage = "";
if (inputValue === null || inputValue === "") {
errorMessage = "This field is empty.";
}
if (inputValue !== "") {
if (inputValue.length < 3) {
errorMessage = "This field has less than 3 characters.";
}
}
renderErrorMessage(elemPos, errorMessage);
if (errorMessage !== "") {
return false
}
return true
}
function checkEmail(input) {
let elemPos = document.getElementById("email");
let emailValue = input.value;
let errorMessage = "";
let regex = /^(([^<>()\[\]\\.,;:\s#"]+(\.[^<>()\[\]\\.,;:\s#"]+)*)|(".+"))#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
if (!emailValue.match(regex)) {
errorMessage = "Not a valid email address.";
}
if (emailValue === "") {
errorMessage = "This field is empty.";
}
renderErrorMessage(elemPos, errorMessage);
if (errorMessage !== "") {
return false
}
return true
}
function checkPhone(input) {
let elemPos = input.phone;
let phoneValue = input.phone.value;
let errorMessage = "";
let regex = /^(((\+44\s?\d{4}|\(?0\d{4}\)?)\s?\d{3}\s?\d{3})|((\+44\s?\d{3}|\(?0\d{3}\)?)\s?\d{3}\s?\d{4})|((\+44\s?\d{2}|\(?0\d{2}\)?)\s?\d{4}\s?\d{4}))(\s?\#(\d{4}|\d{3}))?$/;
if (!phoneValue.match(regex)) {
errorMessage = "Not a valid UK phone number.";
}
if (phoneValue === "") {
errorMessage = "This field is empty.";
}
renderErrorMessage(elemPos, errorMessage);
if (errorMessage !== "") {
return false
}
return true
}
function renderErrorMessage(selectedElem, errorMessage) {
let errorElem = document.createElement("span");
errorElem.setAttribute("class", "error");
let errorText = document.createTextNode(errorMessage);
errorElem.appendChild(errorText);
selectedElem.parentNode.insertBefore(errorElem, selectedElem.nextSibling);
return selectedElem;
}
function cleanUpErrors() {
let indicator = document.getElementsByTagName("span");
for (let i = 0; i < indicator.length; i++) {
indicator[i].setAttribute("class", "hide");
}
}
label, .error, button {
display: block;
}
<form id="form" action="test3success.html" novalidate="novalidate">
<label for="firstName">First Name (required)</label>
<input id="firstName" type="text" name="text" required>
<label for="lastName">Last Name (required)</label>
<input id="lastName" type="text" name="text" required>
<label for="email">Email (required)</label>
<input id="email" type="email" required>
<label for="phone">Phone Number (required)</label>
<input id="phone" type="tel" required>
<button type="submit">Submit</button>
</form>

Javascript is partially working and isn't returning an answer

My javascript code is partially working, it works on the first name validation, on the Email validation it shows the error for a second but it doesn't return false and the password validation isn't working at all.
function validate() {
var emailOk = validateEmail();
var fNameOk = validateFirstName();
var paswOk = validatePassword();
return fNameOk;
return paswOk;
return emailOk;
}
function validatePassword() {
var name = document.getElementById("psw");
name.style.borderColor = "";
document.getElementById("passwordErr").innerText = "";
if (name.value.length < 7) {
name.style.borderColor = "red";
var error = document.getElementById("passwordErr");
error.innerText = "Password does not fit the criteria.";
return false;
}
else
return true;
}
function validateFirstName() {
var name = document.getElementById("F_Name");
name.style.borderColor = "";
document.getElementById("fNameErr").innerText = "";
if (name.value.length == 0) {
name.style.borderColor = "red";
var error = document.getElementById("fNameErr");
error.innerText = "Missing first name.";
return false;
}
else
return true;
}
function validateEmail() {
var name = document.getElementById("email");
name.style.borderColor = "";
document.getElementById("emailErr").innerText = "";
var re = /\S+#\S+\.\S+/;
if (re.test(name) == true)
return true;
else
var error = document.getElementById("emailErr");
error.innerText = "Not a vaild email.";
return false;
}
I expect it to stop when you enter a password that is shorter than 7 and for it to show the message. I also expect it to stop when The email is invalid.
You are writing your else statements incorrectly. They should also be opened and closed with curly brackets
else { // code }
Also, code written after a return statement will not be executed. You will need to return 3 variables at the same time, using an object or array.
function validate() {
var emailOk = validateEmail();
var fNameOk = validateFirstName();
var paswOk = validatePassword();
console.log(fNameOk, paswOk, emailOk)
return {
fNameOk,
paswOk,
emailOk
}
}
function validatePassword() {
var name = document.getElementById("psw");
name.style.borderColor = "";
document.getElementById("passwordErr").innerText = "";
if (name.value.length < 7) {
name.style.borderColor = "red";
var error = document.getElementById("passwordErr");
error.innerText = "Password does not fit the criteria.";
return false;
} else {
return true;
}
}
function validateFirstName() {
var name = document.getElementById("F_Name");
name.style.borderColor = "";
document.getElementById("fNameErr").innerText = "";
if (name.value.length == 0) {
name.style.borderColor = "red";
var error = document.getElementById("fNameErr");
error.innerText = "Missing first name.";
return false;
} else {
return true;
}
}
function validateEmail() {
var name = document.getElementById("email");
name.style.borderColor = "";
document.getElementById("emailErr").innerText = "";
var re = /\S+#\S+\.\S+/;
if (re.test(name) == true) {
return true;
} else {
var error = document.getElementById("emailErr");
error.innerText = "Not a vaild email.";
return false;
}
}
<input id="email" placeholder="Email" /><br>
<input id="F_Name" placeholder="First Name" /><br>
<input id="psw" type="password" placeholder="Password" /><br>
<button onclick="validate()">Register</button>
<div id="passwordErr"></div>
<div id="fNameErr"></div>
<div id="emailErr"></div>
One thing I can say, use:
return fNameOk && paswOk && emailOk;
instead of:
return fNameOk;
return paswOk;
return emailOk;
Because when you write "return fNameOk;", it will return from the function. The next two lines will never be executed.

Retrieving ajax data synchronously back to calling function

I have a form featuring the google captcha code: http://code.google.com/p/cool-php-captcha.
As this captcha uses a session to store the captcha I am having difficulty retrieving the upto date variable of the session into javascript through ajax. It was working well when my ajax command was using the async: false flag but as this is being depreciated I would rather not use it.
My problem at the moment is that I am trying to use a callback function to retrieve the value but by trying to send the value back to the original function I am creating a loop between my 2 functions and can't quite figure out the best way to get what I want.
thanks for any help cheers Callum
<script type="text/javascript">
function getcaptchsession()
{
$.ajax({url:'/Includes/Session.php', cache:false, type: 'GET', success:function(data, status, XHR){validate(data);}});
}
function validate(data)
{
var session = data;
var ok = '';
var nameerror = '';
var emailerror = '';
var subjecterror = '';
var messageerror = '';
var contactform = document.forms.ContactForm;
var fullname = contactform.Fullname.value;
var emailadd = contactform.Emailadd.value;
var subject = contactform.Subject.value;
var message = contactform.Message.value;
var captcha = contactform.CaptchaText.value;
getcaptchsession();
if (fullname == "")
{
var x = document.getElementsByClassName("error");
x[0].innerHTML = "Name field is a required field.";
nameerror = true;
}
else if (fullname != "")
{
if (/[^a-z\s-]/i.test(fullname))
{
var x = document.getElementsByClassName("error");
x[0].innerHTML = "Alphabetic characters only.";
nameerror = true;
}
else
{
var x = document.getElementsByClassName("error");
x[0].innerHTML = "";
nameerror = false;
}
}
if (emailadd == "")
{
var x = document.getElementsByClassName("error");
x[1].innerHTML = "Email field is a required field.";
emailerror = true;
}
else if (emailadd != "")
{
if (/^\w+([\.-]?\w+)*#\w+([\.-]?\w+)*(\.\w{2,3})+$/.test(emailadd))
{
var x = document.getElementsByClassName("error");
x[1].innerHTML = "";
emailerror = false;
}
else
{
var x = document.getElementsByClassName("error");
x[1].innerHTML = "Email is not a valid email address.";
nameerror = true;
}
}
if (subject == "")
{
var x = document.getElementsByClassName("error");
x[2].innerHTML = "Subject field is a required field.";
subjecterror = true;
}
else
{
var x = document.getElementsByClassName("error");
x[2].innerHTML = "";
subjecterror = false;
}
if (message == "")
{
var x = document.getElementsByClassName("error");
x[3].innerHTML = "Message field is a required field.";
messageerror = true;
}
else
{
var x = document.getElementsByClassName("error");
x[3].innerHTML = "";
messageerror = false;
}
if (captcha == "")
{
var x = document.getElementsByClassName("error");
x[4].innerHTML = "The captcha field is a required field.";
messageerror = true;
}
else if (captcha != "")
{
if (captcha != session)
{
var x = document.getElementsByClassName("error");
x[4].innerHTML = "Captcha mismatch.";
messageerror = true;
}
else
{
var x = document.getElementsByClassName("error");
x[4].innerHTML = "";
messageerror = false;
}
}
if (nameerror == true || emailerror == true || subjecterror == true || messageerror == true || captcha == true)
{
return false;
}
else
{
return true;
}
}
</script>
My form is as follows:
<form id="ContactForm" name="ContactForm" action="javascript:loadDoc();" onsubmit="return(validate());">
<label for="Fullname">Name <span class="red">*</span><span class="error"></span></label>
<input id="ContactFormInput" name="Fullname" class="text" id="Fullname">
<label for="Emailadd">Email <span class="red">*</span><span class="error"></span></label>
<input id="ContactFormInput" name="Emailadd" class="text" id="Emailadd">
<label for="Subject">Subject <span class="red">*</span><span class="error"></span></label>
<input id="ContactFormInput" name="Subject" class="text" id="Subject">
<label for="Message">Message <span class="red">*</span><span class="error"> </span></label>
<textarea id="Message" name="Message" rows="6" cols="30"></textarea>
<label for="CaptchaText" id="captchalabel">Captcha <span class="red">*</span><span class="error"></span></label>
<div id="CaptchaParent">
<div id="CaptchaIframe">
<img src="/Includes/captcha.php" id="captcha" />
</div><div id="CaptchaReload">
<img class="captchareload" src="/Images/Contact_Us/reload_icon.png" onclick="document.getElementById('captcha').src='/Includes/captcha.php?'+Math.random()">
</div><div id="CaptchaInput">
<input name="CaptchaText" id="CaptchaText" maxlength="8" class="text">
</div>
</div>
<div id="ContactInput">
<input id="Submit" class="ContactButton" type="submit" name="submit" class="button" value="Send Now"/>
</div>
</form>
My php session page has
<?php
session_start();
echo $_SESSION['captcha'];
?>

Can't figure out what's wrong with this if statement?

I'm trying to make a form in which, when the user fills out all fields, the output results in a compilation of all of their entered data. The form connects to a php file and it runs just fine, however when I tried to add validation the submit acts strangely.
Basically my "Validation" is made of multiple if statements with one else. The title and content validation are in perfect working order,but when it comes to the type it submits the form anyway.
Any suggestions?
HTML Code:
<body>
<form id="documentationForm" action="testingPHP2.php" method="post">
<figcaption>
<p><strong>Instructions:</strong>
</p>
<p><i>Fill out the information as needed below. Place each step on a new line. When you are finished,<br>submit the document and download the file.</p></i>
</figcaption>
<strong>Title:</strong>
<input id="docTitle" type="text" name="docTitle"><span id="errorTitle"></span>
<br>
<strong>Type:</strong>
<select id="docType" onchange="adaptiveLabel()" name="docType">
<br>
<option value="" selected>Select Document Type</option>
<option value="Procedure">Procedure</option>
<option value="Instruction">Instruction</option>
<option value="Form">Form</option>
</select><span id="errorType"></span>
<br>
<script>
function adaptiveLabel() {
var chosenType = document.getElementById("docType");
var chosenTypeVal = chosenType.value;
var x = document.getElementById("contentLabel");
if (chosenTypeVal == "Procedure") {
x.innerHTML = "Procedural Steps:";
}
if (chosenTypeVal == "Instruction") {
x.innerHTML = "Steps:"
}
if (chosenTypeVal == "Form") {
x.innerHTML = "Form Parts:";
}
if (chosenTypeVal == " ") {
x.innerHTML = " ";
}
}
function submitInputs() {
var errorTitletext = document.getElementById("docTitle");
var errorTitleLable = document.getElementById("errorTitle");
var errorContenttext = document.getElementById("docInput");
var errorContentLabel = document.getElementById("errorContent");
var errorTypetext = document.getElementById("docType");
var errorTypetextLable = document.getElementById("errorType");
if (errorTypetext.value === "") {
alert("You must select a type");
errorTypetextLable.innerHTML = "*Please select a type";
errorTypetextLable.style.color = "red";
}
if (errorTypetext.value === "Procedure" || errorTypetext.value === "Form" || errorTypetext.value === "Instruction") {
errorTypetextLable.innerHTML = "";
errorTypetextLable.style.color = "";
}
if (errorTitletext.value.length === 0 || errorTitletext.value === " ") {
alert("You must create a title");
errorTitleLable.innerHTML = "*Please create a title";
errorTitleLable.style.color = "red";
}
if (errorTitletext.value.length > 0) {
errorTitleLable.innerHTML = "";
errorTitleLable.style.color = "";
}
if (errorContenttext.value.length === 0) {
alert("You must enter content");
errorContentLabel.innerHTML = "*Please enter content";
errorContentLabel.style.color = "red";
}
if (errorContenttext.value.length > 0) {
errorContentLabel.innerHTML = "";
errorContentLabel.style.color = "";
} else {
document.getElementById("documentationForm").submit();
}
}
</script>
<strong><span id="contentLabel"></span><span id="errorContent"></span></strong>
<br>
<textarea style="width: 500px; height: 250px;" id="docInput" name="docInput"></textarea>
<br>
<input type="button" onclick="submitInputs()" value="Create Document">
<input type="submit" value="Default Submit">
</form>
</body>
You should submit the form only if all the values are valid, so use a flag as given below. Also it will be easier to use if...else construct to handle invalid & valid case of a field.
In you logic the problem is irrespective of the first 2 fields valid state, if the content is valid the form's submit is called.
function submitInputs() {
var errorTitletext = document.getElementById("docTitle");
var errorTitleLable = document.getElementById("errorTitle");
var errorContenttext = document.getElementById("docInput");
var errorContentLabel = document.getElementById("errorContent");
var errorTypetext = document.getElementById("docType");
var errorTypetextLable = document.getElementById("errorType");
var valid = true;
if (errorTypetext.value === "") {
alert("You must select a type");
errorTypetextLable.innerHTML = "*Please select a type";
errorTypetextLable.style.color = "red";
valid = false;
} else {
errorTypetextLable.innerHTML = "";
errorTypetextLable.style.color = "";
}
if (errorTitletext.value.length === 0 || errorTitletext.value === " ") {
alert("You must create a title");
errorTitleLable.innerHTML = "*Please create a title";
errorTitleLable.style.color = "red";
valid = false;
} else {
errorTitleLable.innerHTML = "";
errorTitleLable.style.color = "";
}
if (errorContenttext.value.length === 0) {
alert("You must enter content");
errorContentLabel.innerHTML = "*Please enter content";
errorContentLabel.style.color = "red";
valid = false;
} else {
errorContentLabel.innerHTML = "";
errorContentLabel.style.color = "";
}
if (valid) {
document.getElementById("documentationForm").submit();
}
}
Demo: Fiddle
Also There is no need to have a default submit button, you can have only one button like
<form id="documentationForm" action="testingPHP2.php" method="post" onsubmit="return submitInputs();">
.....
<input type="submit" value="Create Document" />
</form>
then
function submitInputs() {
var errorTitletext = document.getElementById("docTitle");
var errorTitleLable = document.getElementById("errorTitle");
var errorContenttext = document.getElementById("docInput");
var errorContentLabel = document.getElementById("errorContent");
var errorTypetext = document.getElementById("docType");
var errorTypetextLable = document.getElementById("errorType");
var valid = true;
if (errorTypetext.value === "") {
alert("You must select a type");
errorTypetextLable.innerHTML = "*Please select a type";
errorTypetextLable.style.color = "red";
valid = false;
} else {
errorTypetextLable.innerHTML = "";
errorTypetextLable.style.color = "";
}
if (errorTitletext.value.length === 0 || errorTitletext.value === " ") {
alert("You must create a title");
errorTitleLable.innerHTML = "*Please create a title";
errorTitleLable.style.color = "red";
valid = false;
} else {
errorTitleLable.innerHTML = "";
errorTitleLable.style.color = "";
}
if (errorContenttext.value.length === 0) {
alert("You must enter content");
errorContentLabel.innerHTML = "*Please enter content";
errorContentLabel.style.color = "red";
valid = false;
} else {
errorContentLabel.innerHTML = "";
errorContentLabel.style.color = "";
}
return valid;
}
Demo: Fiddle

Categories

Resources