Retrieving ajax data synchronously back to calling function - javascript

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'];
?>

Related

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>

InnerHTML in multiple fiields and more than one error statements

I am having trouble trying to get the form to validate using the onblur handler.
What I am trying to do is to get the first and last name field to display an error message if the field is blank, if it’s less than 5 , more than 18 characters, or it the user enters a number.
I would like to be able to do this using only one function so I do not need to do this for seperate functions.
Eg:
function ValidateName(field) {
var field = field.value;
var output = document.getElementById("fnameError");
if (field == "")
{
output = "field can’t be blank.";
return false;
}
else
{
output = "";
}
}
<form>
<input type="Text" id="Fname" onblur="ValidateName(this)">
<span id="fnameError"></span>
</form>
Your answer according to the question.
function ValidateName(field) {
var output = document.getElementById("fnameError");
if (field.value == "")
{
output.innerHTML = "field can’t be blank.";
}
else
{
output.innerHTML = "";
}
}
<form>
<input type="Text" id="Fname" onblur="ValidateName(this)">
<span id="fnameError"></span>
</form>
Your answer according to the the comment made on my answer.
function ValidateName() {
var outputF = document.getElementById("fnameError");
var outputL = document.getElementById("lnameError");
var outputB = document.getElementById("BothError");
var field1 = document.getElementById("Fname");
var field2 = document.getElementById("Lname");
if (field1.value == "" && field2.value == "")
{
outputF.innerHTML = "";
outputB.innerHTML = "No field can be left blank.";
outputL.innerHTML = "";
}
else if (field1.value !== "" && field2.value == "")
{
outputF.innerHTML = "";
outputB.innerHTML = "";
outputL.innerHTML = "field can’t be blank.";
}
else if (field1.value == "" && field2.value !== "")
{
outputF.innerHTML = "field can’t be blank.";
outputB.innerHTML = "";
outputL.innerHTML = "";
}
else {
outputF.innerHTML = "";
outputB.innerHTML = "";
outputL.innerHTML = "";
}
}
<form>
<input type="Text" id="Fname" onblur="ValidateName()">
<span id="fnameError"></span>
<br><br>
<input type="Text" id="Lname" onblur="ValidateName()">
<span id="lnameError"></span>
<br><br>
<span id="BothError"></span>
</form>
you can try this also
function validateform(){
var name=document.myform.name.value;
if (name==null || name==""){
alert("Name can't be blank");
return false;
}
else if(name.length < 5){
alert("name must be atleast 8 characters long");
return false;
}
else if(name.length <18){
alert("text must be more than 18 characters");
return false;
}
}
<form name="myform" method="post" action="" onsubmit="return validateform()" >
Name: <input type="text" name="name"><br/>
<input type="submit" value="register">
</form>

document.getElementById is not working for a form

I have some code like this:
HTML
<div id = "inputs" style="width:300px;">
<form id = "changePwForm" name = "changePwForm" method = "POST" action = "me.php">
<input type = "password" id = "currentPw" name = "currentPw" class="loginBlank" style = "width:300px;margin-top:0px;" placeholder="Current Password"/>
<input type = "password" id = "newPw" name = "newPw" class="loginBlank" style = "width:300px;margin-top:10px;" placeholder="New password"/>
<input type = "password" id = "newPwCheck" name = "newPwCheck" class="loginBlank" style = "width:300px;margin-top:10px;" placeholder="Retype new password"/>
<input type = "button" id = "submitBtn" onclick = "checkChangeForm()" class = "loginBlank" value = "Confirm" style = "width:300px;margin-top:10px;font-size:16px;" />
</form>
</div>
JavaScript
function checkChangeForm() {
var current = document.getElementById("currentPw").value;
var newPw = document.getElementById("newPw").value;
var newPwCheck = document.getElementById("newPwCheck").value;
if (current != "" && newPw != "" && newPwCheck != "") {
if (newPw == newPwCheck) {
if (newPw.length >= 8) {
alert("OK");
document.getElementById("changePwForm").submit();
} else {
alert("Passwords must be longer than 8 characters.");
document.getElementById("currentPw").value = "";
document.getElementById("newPw").value = "";
document.getElementById("newPwCheck").value = "";
document.getElementById("newPw").focus();
}
} else {
alert("The password does not match!");
document.getElementById("newPw").value = "";
document.getElementById("newPwCheck").value = "";
document.getElementById("newPw").focus();
}
} else {
alert("No password entered");
document.getElementById("currentPw").value = "";
document.getElementById("newPw").value = "";
document.getElementById("newPwCheck").value = "";
document.getElementById("currentPw").focus();
}
}
Supposing that by the time the button is pressed, the form would have been loaded, and when the variable is created by document.getElementById("changePwForm") again, it should be existing. However, it returned NULL. Why? What is wrong here?
Fiddle: https://jsfiddle.net/fL0z59o3/#&togetherjs=FAKVrL1jG3
Inline-events expect function to be in global-scope, not under the scope of window.onload
If you want to go on with window.onload, bind event using addEventListener or Element.onEVENT_NAME
document.getElementById('submitBtn').addEventListener('click',checkChangeForm);
document.getElementById('submitBtn').addEventListener('click',checkChangeForm);
function checkChangeForm() {
var current = document.getElementById("currentPw").value;
var newPw = document.getElementById("newPw").value;
var newPwCheck = document.getElementById("newPwCheck").value;
if (current != "" && newPw != "" && newPwCheck != "") {
if (newPw == newPwCheck) {
if (newPw.length >= 8) {
alert("OK");
document.getElementById("changePwForm").submit();
} else {
alert("Passwords must be longer than 8 characters.");
document.getElementById("currentPw").value = "";
document.getElementById("newPw").value = "";
document.getElementById("newPwCheck").value = "";
document.getElementById("newPw").focus();
}
} else {
alert("The password does not match!");
document.getElementById("newPw").value = "";
document.getElementById("newPwCheck").value = "";
document.getElementById("newPw").focus();
}
} else {
alert("No password entered");
document.getElementById("currentPw").value = "";
document.getElementById("newPw").value = "";
document.getElementById("newPwCheck").value = "";
document.getElementById("currentPw").focus();
}
}
<div id="inputs" style="width:300px;">
<form id="changePwForm" name="changePwForm" method="POST" action="me.php">
<input type="password" id="currentPw" name="currentPw" class="loginBlank" style="width:300px;margin-top:0px;" placeholder="Current Password" />
<input type="password" id="newPw" name="newPw" class="loginBlank" style="width:300px;margin-top:10px;" placeholder="New password" />
<input type="password" id="newPwCheck" name="newPwCheck" class="loginBlank" style="width:300px;margin-top:10px;" placeholder="Retype new password" />
<input type="button" id="submitBtn" class="loginBlank" value="Confirm" style="width:300px;margin-top:10px;font-size:16px;" />
</form>
</div>
Without window.onload
function checkChangeForm() {
var current = document.getElementById("currentPw").value;
var newPw = document.getElementById("newPw").value;
var newPwCheck = document.getElementById("newPwCheck").value;
if (current != "" && newPw != "" && newPwCheck != "") {
if (newPw == newPwCheck) {
if (newPw.length >= 8) {
alert("OK");
document.getElementById("changePwForm").submit();
} else {
alert("Passwords must be longer than 8 characters.");
document.getElementById("currentPw").value = "";
document.getElementById("newPw").value = "";
document.getElementById("newPwCheck").value = "";
document.getElementById("newPw").focus();
}
} else {
alert("The password does not match!");
document.getElementById("newPw").value = "";
document.getElementById("newPwCheck").value = "";
document.getElementById("newPw").focus();
}
} else {
alert("No password entered");
document.getElementById("currentPw").value = "";
document.getElementById("newPw").value = "";
document.getElementById("newPwCheck").value = "";
document.getElementById("currentPw").focus();
}
}
<div id="inputs" style="width:300px;">
<form id="changePwForm" name="changePwForm" method="POST" action="me.php">
<input type="password" id="currentPw" name="currentPw" class="loginBlank" style="width:300px;margin-top:0px;" placeholder="Current Password" />
<input type="password" id="newPw" name="newPw" class="loginBlank" style="width:300px;margin-top:10px;" placeholder="New password" />
<input type="password" id="newPwCheck" name="newPwCheck" class="loginBlank" style="width:300px;margin-top:10px;" placeholder="Retype new password" />
<input type="button" id="submitBtn" onclick="checkChangeForm()" class="loginBlank" value="Confirm" style="width:300px;margin-top:10px;font-size:16px;" />
</form>
</div>
include your script just near the end of the body tag, and see if it works.
Just found the problem... I nested the <form> element in another <form> element... Removing the outer one made it work.
Please move your script just near the end of the body tag
<body>
<div id = "inputs" style="width:300px;">
<form id = "changePwForm" name = "changePwForm" method = "POST" action = "me.php">
........
</form>
<script>
function checkChangeForm() {
.....
}
</script>
</div>
</body>

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

Radio Buttons with JavaScript in a Form

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;
}

Categories

Resources