Ajax success function is not working properly - javascript

I've made a simple ajax/php form and my success function is not working properly for some reason. Im still getting emails, so i guess the condition is true, but the is not appearing and the submit button is not blocked. Here's my code:
function myFunction() {
var name = document.getElementById("name").value;
var message = document.getElementById("message").value;
var company = document.getElementById("company").value;
var phone = document.getElementById("phone").value;
// Returns successful data submission message when the entered information is stored in database.
var dataString = 'name1=' + name + '&message1=' + message + '&company1=' + company + '&phone1=' + phone;
if (name == '' || message == '' || company == '' || phone == '') {
document.getElementById("error").style="display: block; color: red;";
} else {
// AJAX code to submit form.
$.ajax({
type: "POST",
url: "email.php",
data: dataString,
cache: false,
success: function() {
document.getElementById("success").style="display: block; color: green;";
}
});
}
return false;
}
<!DOCTYPE HTML>
<html>
<head>
<meta charset="utf-8">
<title>AJAX + PHP форма</title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<style type="text/css">
.input_group {
display:inline-block;
padding: 5px;
width:100%;
text-align: center;
}
form {
width: 50%;
}
#send_message {
text-align: center;
}
</style>
</head>
<body>
<form id="contact" action="">
<fieldset>
<legend>AJAX + PHP форма</legend>
<div class = "input_group">
<label for="name" id="name_label">Имя</label> <br/>
<input type="text" name="name" id="name" size="50" value="" class="text-input" required = "required"/>
</div>
<br/>
<div class = "input_group">
<label for="company" id="company_label">Компания</label> <br/>
<input type="text" name="company" id="company" size="50" value="" class="text-input" required = "required" />
</div>
<br/>
<div class = "input_group">
<label for="phone" id="phone_label">Телефон</label> <br/>
<input type="text" name="phone" id="phone" size="50" value="" class="text-input" required = "required" />
</div>
<br/>
<div class = "input_group">
<label for="msg_text" id="msg_label">Запрос</label> <br/>
<textarea rows="6" cols="51" name="question" id="message" required = "required"></textarea>
</div>
<div class = "input_group">
<input type="submit" onclick="myFunction()" id="submit" value="Отправить" />
</div>
</fieldset>
</form>
<h2 style="display:none;" id ="error">Заполните все поля!</h2>
<h2 style="display:none;" id="success">Message sent!</h2>
List item

You can't set the style attribute as a string with el.style. Either set each style individually (.style.display,. style.color,...) or use
$('#success').css({display: 'block', color: 'green'})

this is your final code which working fine for me
<!DOCTYPE HTML>
<html>
<head>
<meta charset="utf-8">
<title>AJAX + PHP форма</title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<style type="text/css">
.input_group {
display:inline-block;
padding: 5px;
width:100%;
text-align: center;
}
form {
width: 50%;
}
#send_message {
text-align: center;
}
</style>
</head>
<body>
<form id="contact" action="">
<fieldset>
<legend>AJAX + PHP форма</legend>
<div class = "input_group">
<label for="name" id="name_label">Имя</label> <br/>
<input type="text" name="name" id="name" size="50" value="" class="text-input" required = "required"/>
</div>
<br/>
<div class = "input_group">
<label for="company" id="company_label">Компания</label> <br/>
<input type="text" name="company" id="company" size="50" value="" class="text-input" required = "required" />
</div>
<br/>
<div class = "input_group">
<label for="phone" id="phone_label">Телефон</label> <br/>
<input type="text" name="phone" id="phone" size="50" value="" class="text-input" required = "required" />
</div>
<br/>
<div class = "input_group">
<label for="msg_text" id="msg_label">Запрос</label> <br/>
<textarea rows="6" cols="51" name="question" id="message" required = "required"></textarea>
</div>
<div class = "input_group">
<input type="button" onclick="myFunction()" id="submit" value="Отправить" />
</div>
</fieldset>
</form>
<h2 style="display:none;" id ="error">Заполните все поля!</h2>
<h2 style="display:none;" id="success">Message sent!</h2>
<script>
function myFunction() {
var name = document.getElementById("name").value;
var message = document.getElementById("message").value;
var company = document.getElementById("company").value;
var phone = document.getElementById("phone").value;
// Returns successful data submission message when the entered information is stored in database.
var dataString = 'name1=' + name + '&message1=' + message + '&company1=' + company + '&phone1=' + phone;
if (name == '' || message == '' || company == '' || phone == '') {
document.getElementById("error").style="display: block; color: red;";
} else {
// AJAX code to submit form.
$.ajax({
type: "POST",
url: "demo.php",
data: dataString,
cache: false,
success: function(data) {
alert(data)
$('#success').css({display: 'block', color: 'green'});
}
});
}
return false;
}
</script>
and this is demo php file
<?php
print_r($_REQUEST);
?>
just update button type submit to button

Related

Need to correct this form validation

I've this small form in which the 1st field(title) is required by default. The 2nd and the 3rd are required only in a specific condition.
Case-I: If tool name is filled out, both tool name & tool URL become required.
Case-II: If tool URL is filled out, both tool name & tool URL become required.
I'm not sure it is working as expected.
Could you please help me correct my code?
$(document).ready(function(){
articleTitle = $('#title').val();
toolName = $('#toolName').val().trim();
toolURL = $('#toolURL').val();
if(((toolName.length>0)&&(toolURL==="")) || ((toolName.length<=0)&&(toolURL!==""))){
$('#toolName').prop('required', true);
$('#toolURL').prop('required' , true);
} else {
$('#toolName').prop('required', false);
$('#toolURL').prop('required', false);
}
$("#myForm").submit(function(){
sayHello();
return false;
});
});
label {
float: left;
width: 100px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.0/jquery.min.js"></script>
<form id="myForm">
<label for="title">Title:</label> <input type="text" id="title" required> <br /><br />
<label for="toolName">Tool Name: </label><input type="text" id="toolName"> <br /> <br />
<label for="toolURL">Tool URL: </label><input type="url" id="toolURL"> <br /> <br />
<button>Submit</button>
</form>
You can simplify your code quite a bit, please see the comments for a description.
var $toolName = $('#toolName')
var $toolURL = $('#toolURL')
var $toolInputs = $($toolName).add($toolURL)
function sayHelloToMyLittleFriend() {
alert('sup! form was submitted')
}
$toolInputs.on('change', function(e) {
var toolName = $toolName.val()
var toolURL = $toolURL.val()
$toolInputs.prop('required', toolName || toolURL)
})
$('form').submit(function(e) {
var toolName = $toolName.val()
var toolURL = $toolURL.val()
var bothFilled = !!toolName && !!toolURL
var noneFilled = !toolName && !toolURL
if (bothFilled || noneFilled) {
sayHelloToMyLittleFriend()
return true
}
return false
})
label {
float: left;
width: 100px;
}
/* this will show what element has the required attribute */
[required] {
border: 1px solid red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.0/jquery.min.js"></script>
<form id="myForm">
<label for="title">Title:</label> <input type="text" id="title" required> <br /><br />
<label for="toolName">Tool Name: </label><input type="text" id="toolName"> <br /> <br />
<label for="toolURL">Tool URL: </label><input type="url" id="toolURL"> <br /> <br />
<button>Submit</button>
</form>
Here is a straightforward approach using library-less javascript (rather than jQuery).
(Albeit, you'll see that it's very similar to the jQuery).
Whenever data is entered into or removed from the form, the form inputs are checked and, as appropriate, the required attributes are added or removed.
var myForm = document.getElementById('myForm');
var toolName = document.getElementById('toolName');
var toolURL = document.getElementById('toolURL');
function checkInputs() {
if ((toolName.value !== '') || (toolURL.value !== '')) {
toolName.setAttribute('required','required');
toolURL.setAttribute('required','required');
}
if ((toolName.value === '') && (toolURL.value === '')) {
toolName.removeAttribute('required');
toolURL.removeAttribute('required');
}
}
myForm.addEventListener('keyup', checkInputs, false);
<form id="myForm">
<label for="title">Title:</label> <input type="text" id="title" required> <br /><br />
<label for="toolName">Tool Name: </label><input type="text" id="toolName"> <br /> <br />
<label for="toolURL">Tool URL: </label><input type="url" id="toolURL"> <br /> <br />
<input type="submit" value="Submit" />
</form>

Javascript Error message flashes for only a second [duplicate]

This question already has answers here:
What is the meaning of onsubmit="return false"? (JavaScript, jQuery)
(4 answers)
Closed 5 years ago.
I have this HTML project that validates an empty form. The error is being displayed on the side of the inputs but only flashes for a second. I just want the error of the messages to be displayed once
This is my HTML code with the necessary links:
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>JavaScript - JQuery </title>
<link rel="stylesheet" type="text/css" href="contactform.css">
</head>
<body>
<h1 id="pageheading">Zedland Health Authority</h1>
<h2 class="sectionheading">Contact Form</h2>
<form id="register">
<fieldset id="controls">
<div>
<label class="formlabel" for="fname">First Name: </label>
<input id="fname" type="text" size="30" placeholder="First name"
autofocus>
<p id="fname-error" class="error" style="display:none; color:red;">*
You must enter a first name.</p>
</div>
<div>
<label class="formlabel"for="lname">Last Name: </label>
<input id="lname" type="text" size="30">
<p id="lname-error" class="error" style="display:none; color:red;">*
You must enter a Last name.</p>
</div>
<div>
<label class="formlabel" for="title">Title: </label>
<select id="title">
<option value="Mr">Mr.</option>
<option value="Ms">Ms.</option>
<option value="Mrs">Mrs.</option>
<option value="Miss">Miss.</option>
<option value="Master">Master.</option>
</select>
</div>
<div>
<label class="formlabel" for="heathauthoritynumber"><span>
<img src="tooltip.png" id="qmark" alt="Hint"></span>
Health Authority Number:
</label>
<input id="healthauthoritynumber" type="text" size="10">
<p id="hn-error" class="error" style="display:none; color:red;">*You
must enter a Health Authority Number eg('ZHA345742)</p>
<div class="tooltip" id="ttip">If you do not know your ZHA number
,please contact your GP</div>
</div>
<div>
<label class="formlabel" for="email">Email: </label>
<input id="email" type="text" size="40">
<p id="email-error" class="error" style="display:none; color:red;">You
must enter email</p>
</div>
<div>
<label class="formlabel" for="telephone">Telephone Number: </label>
<input id="telephone" type="text" size="40">
<p id="tele-error" class="error" style="display:none; color:red;">You
must enter a telephone</p>
</div>
<div class="formlabel">
<input id="submit-button" type="submit" value="Submit" >
</div>
</fieldset>
</form>
<script src="contactform.js"></script>
</body>
</html>
This is my Javascript
function onSubmit(){
console.log("ive been submitted");
checkEmpty(document.getElementById('fname'),document.getElementById("fname-error"));
checkEmpty(document.getElementById('lname'),document.getElementById("lname-error"));
checkEmpty(document.getElementById('healthauthoritynumber'),document.getElementById("hn-error"));
checkEmpty(document.getElementById('email'),document.getElementById("email-error"));
checkEmpty(document.getElementById('telephone'),document.getElementById("tele-error"));
//checkValidHealthID(document.getElementById('healthauthoritynumber'),document.getElementById("hn-error"));
}
// Read about regular expressions using: https://developer.mozilla.org/en/docs/Web/JavaScript/Guide/Regular_Expressions
// and http://stackoverflow.com/questions/25155970/validating-uk-phone-number-regex-c
function checkValidHealthID(inputID, errorID){
var re = new RegExp('/ZHA\d{6}$/');
if((inputID.value)!== re){
errorID.style.display = "inline";
}else
{
errorID.style.display = "none";
}
}
function checkEmpty(inputID, errorID){
//Default behaviour at for FORM is to reload the HTML page
//e.preventDefault();
console.log("checking empty");
if((inputID.value === "") || (inputID.value.length === 0)){
console.log("empty!!");
errorID.style.display = "inline";
}
else
{
errorID.style.display = "none";
}
}
function textHint(txtElem, defaultText) {
txtElem.value = defaultText;
txtElem.style.color = "#A8A8A8";
txtElem.style.fontStyle = "italic";
txtElem.onfocus = function() {
if (this.value === defaultText) {
this.value = "";
this.style.color = "#000";
this.style.fontStyle = "normal";
}
}
txtElem.onblur = function() {
if (this.value === "") {
this.value = defaultText;
this.style.color = "#A8A8A8";
this.style.fontStyle = "italic";
}
}
}
function textHints() {
//textHint(document.getElementById("firstName"), "Enter your first name");
textHint(document.getElementById('lname'), "Enter your last name");
textHint(document.getElementById('healthauthoritynumber'), "for eg
,ZHA346783");
textHint(document.getElementById('email'), "Enter your email");
textHint(document.getElementById('telephone'), "Enter your telephone
number");
}
function switchToolTip() {
document.getElementById('qmark').onmouseover = function() {
var toolTip = document.getElementById('ttip');
toolTip.style.display='block';
}
document.getElementById('qmark').onmouseout = function() {
var toolTip = document.getElementById('ttip');
toolTip.style.display='none';
}
}
//windows.onload=textHints();
//windows.onload=switchToolTip();
//window.onload=init;
document.getElementById("submit-button").onclick = onSubmit;
Your form is getting submitted which results in page reload. That's why you see the message flashing for a while. I saw the commented line in your JavaScript
//Default behaviour at for FORM is to reload the HTML page
//e.preventDefault();
You should get uncomment e.preventDefault().
Grab the click event as function onSubmit(event) and pass the event to checkEmpty.

My Jquery does not connect to my html

my jquery is not connecting and I cannot figure out why. I've been stumped on this for hours and I cannot figure it out.
this is my html code. The file name is exercise6.html
<!DOCTYPE html>
<html lang="en">
<head>
<title>Exercise 6</title>
<meta charset="utf-8">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script type="text/javascript" src="JS/exercise6.js"> </script>
</head>
<body>
<form id="email_form" name="email_form" action="exercise6.html" method="get">
<fieldset class="info">
<legend>Contact Information</legend>
<p>
<input type="text" name="Lname" id="name2" value="" required />
<label for="name2"> Last</label>
</p>
<p>
<input type="text" name="mailAddie" id="mail1" value="" required />
<label for="mail1"> Address</label>
</p>
<p>
<input type="text" name="City" id="city1" value="" />
<label for="city1"> City</label>
</p>
<p>
<input type="text" name="State" id="state1" value="" />
<label for="state1"> State</label>
</p>
<p>
<input type="number" name="Zip" id="zip1" value="" />
<label for="zip1"> Zip</label>
</p>
<p>
<input type="number" name="phoneNum" id="number" />
<label for="number"> Phone</label>
</p>
</fieldset>
<fieldset>
<legend>Sign up for our email list</legend>
<p>
<label for="email_address1"> Email Address</label>
<input type="text" name="email_address1" id="email_address1" value="" />
<span>*</span><br>
</p>
<p>
<label for="email_address2"> Confirm Email Address</label>
<input type="text" name="email_address2" id="email_address2" value="" />
<span>*</span><br>
</p>
<p>
<label for="first_name"> First</label>
<input type="text" name="first_name" id="first_name" value="" />
<span>*</span><br>
</p>
</fieldset>
<p>
<label> </label>
<input type="submit" value="Join Our List" id="join_list" >
</p>
</form>
</body>
</html>
and this is my javascript. The file name is exercise6.js and it is located in a file named JS. I do not know what I am doing wrong.
$(document).ready(function() {
$("#join_list").click(function() {
var emailAddress1 = $("#email_address1").val();
var emailAddress2 = $("#email_address2").val();
var isValid = true;
if (emailAddress1 == "") {
$("#email_address1").next().text("This field is required.");
isValid = false;
} else {
$("#email_address1").next().text("");
}
if (emailAddress2 == "") {
$("#email_address2").next().text("This field is required.");
isValid = false;
} else {
$("#email_address2").next().text("");
}
if ($("#first_name").val() == "") {
$("#first_name").next().text("This field is required.");
isValid = false
} else {
$("#first_name").next().text("");
}
if (isValid) {
$("#email_form").submit();
}
)};
)};
Can anyone help me?
The last two lines of exercise6.js both have a syntax error.
Change:
)};
)};
To:
});
});
To find this yourself next time, try using web development IDE like NetBeans with the help of right click with mouse to inspect in browser debug console, which would have even shown you where is this kind of error.
Your js code has some errors for close the function "});" try this
$(document).ready(function() {
$("#join_list").click(function() {
var emailAddress1 = $("#email_address1").val();
var emailAddress2 = $("#email_address2").val();
var isValid = true;
if (emailAddress1 == "") {
$("#email_address1").next().text("This field is required.");
isValid = false;
} else {
$("#email_address1").next().text("");
}
if (emailAddress2 == "") {
$("#email_address2").next().text("This field is required.");
isValid = false;
} else {
$("#email_address2").next().text("");
}
if ($("#first_name").val() == "") {
$("#first_name").next().text("This field is required.");
isValid = false
} else {
$("#first_name").next().text("");
}
if (isValid) {
$("#email_form").submit();
}
});
});

onfocus and onblur events on input

I'm trying to make a contact form, which should apply a class for css transitions when the input is onfocus/clicked by the user. If the user has typed name, the class from onfocus should stay there. If nothing is typed, an onblur event should remove the class and the effect.
I'm trying something like this, but I can't even make the onfocus event tricker an alert for testing my steps...
HTML:
<div>
<form class="footer-contact-form" action="">
<fieldset class="footer-form-field">
<input id="name" class="input-value" name="name" type="text" autocomplete="off" required>
<label for="name">Navn*</label>
</fieldset>
<fieldset class="footer-form-field">
<input id="company" class="input-value" name="company" type="text" autocomplete="off">
<label for="company">Firma</label>
</fieldset>
<fieldset class="footer-form-field">
<input id="email" class="input-value" name="email" type="email" autocomplete="off" required>
<label for="email">E-mail*</label>
</fieldset>
<fieldset class="footer-form-field-txt">
<textarea id="message" class="input-value" name="message" required></textarea>
<label for="message">Besked*</label>
</fieldset>
<input class="footer-msg-send" value="Send Besked" type="submit">
</form>
<button class="fetch-deal">Send</button>
</div>
CSS:
.input-expand {
transition: .7s;
width: 90px;
}
JS:
var inputValue = document.getElementsByClassName("input-value");
inputValue.onfocus = function() {
if (!inputValue.classList.hasClass("input-expand")) {
inputValue.addClass("input-expand");
}
// If no value is added and user does onblurr event, it should remove class .input-expand, otherwise leave class there.
}
var inputValue = document.getElementsByClassName("input-value");
var onFocus = function() { this.classList.add("input-expand");};
var onBlur = function() {if (!this.value) this.classList.remove("input-expand");};
for (var i = 0; i < inputValue.length; i++) {
inputValue[i].addEventListener('focus', onFocus, false);
inputValue[i].addEventListener('blur', onBlur, false);
}
.input-value {
transition: .7s;
width: 45px;
}
.input-expand {
transition: .7s;
width: 90px;
}
<div>
<form class="footer-contact-form" action="">
<fieldset class="footer-form-field">
<input id="name" class="input-value" name="name" type="text" autocomplete="off" required>
<label for="name">Navn*</label>
</fieldset>
<fieldset class="footer-form-field">
<input id="company" class="input-value" name="company" type="text" autocomplete="off">
<label for="company">Firma</label>
</fieldset>
<fieldset class="footer-form-field">
<input id="email" class="input-value" name="email" type="email" autocomplete="off" required>
<label for="email">E-mail*</label>
</fieldset>
<fieldset class="footer-form-field-txt">
<textarea id="message" class="input-value" name="message" required></textarea>
<label for="message">Besked*</label>
</fieldset>
<input class="footer-msg-send" value="Send Besked" type="submit">
</form>
<button class="fetch-deal">Send</button>
</div>
Without jQuery you could try:
var inputValue = document.getElementsByClassName("input-value");
[].forEach.call(inputValue,function(el){
el.onfocus=function() {
if (!el.classList.contains("input-expand")) {
el.className +="input-expand";
}
// If no value is added and user does onblurr event, it should remove class .input-expand, otherwise leave class there.
};
})
or as a fiddle:
https://jsfiddle.net/5v7n4je3/2/
mainly i think you problem lies in the ElementsByClassName array you have to iterate over the elements and use onFocus for every single one.
Notice the new Class is added once for every click at the moment.
I guess better solution for you to use css pseudo-classes. Use css style like below:
.input-value {
transition: .7s;
}
.input-value:focus {
width: 90px;
}
In this case you don't need to handle focus event through js and dynamically change classes of elements.
try this:
$(document).ready(function(){
$(".input-value").focus(function(){
//you focus code here
});
});
more reference: https://api.jquery.com/focus/
Using jQuery, try this :
https://api.jquery.com/focus/
$("input").focus(function() { $(this).addClass("input-expand"); });
$("input").blur(function() { $(this).val?null:$(this).removeClass("input-expand"); });
Here is the fix,
var inputValue = document.getElementsByClassName("input-value");
var onFocus = function() {
if (!this.classList.contains("input-expand")) {
this.classList.add("input-expand");
}
};
var onBlur = function() {
if (this.classList.contains("input-expand")) {
this.classList.remove("input-expand");
}
};
for (var i = 0; i < inputValue.length; i++) {
inputValue[i].addEventListener('focus', onFocus, false);
inputValue[i].addEventListener('blur', onBlur, false);
}
.input-expand {
transition: .7s;
width: 90px;
}
<div>
<form class="footer-contact-form" action="">
<fieldset class="footer-form-field">
<input id="name" class="input-value" name="name" type="text" autocomplete="off" required>
<label for="name">Navn*</label>
</fieldset>
<fieldset class="footer-form-field">
<input id="company" class="input-value" name="company" type="text" autocomplete="off">
<label for="company">Firma</label>
</fieldset>
<fieldset class="footer-form-field">
<input id="email" class="input-value" name="email" type="email" autocomplete="off" required>
<label for="email">E-mail*</label>
</fieldset>
<fieldset class="footer-form-field-txt">
<textarea id="message" class="input-value" name="message" required></textarea>
<label for="message">Besked*</label>
</fieldset>
<input class="footer-msg-send" value="Send Besked" type="submit">
</form>
<button class="fetch-deal">Send</button>
</div>
Try adding the script tag in the end of your body code.
Or else try and implement the solution provided below.
<!DOCTYPE html>
<html>
<head>
<title></title>
<style>
.my-focus-input{
border-color: red;
border-style: solid;
border-width: 1px;
height: 60px;
width: 300px;
}
.my-blur-input{
}
</style>
</head>
<body>
<input onfocus="myFocusFunction(this)" onblur="myBlurFunction(this)">
<script type="text/javascript">
function myFocusFunction(x) {
x.className = "my-focus-input";
}
function myBlurFunction(x) {
x.className = "my-blur-input";
}
</script>
</body>
</html>
Hi you just have to change yours css and js like this:
window.addEventListener("load",function(){
var inputValue = document.getElementsByClassName("input-value");
for(var i=0; i<inputValue.length; i++){
var f = inputValue[i];
f.className = "input-value input-expand";
f.addEventListener("focus", function(){this.style.maxWidth="90px";}, false);
f.addEventListener("blur", function(){if(this.value==""){this.style.maxWidth="30px";}}, false);
}
}, false);
.input-expand {
max-width:30px;
transition:max-width 0.7s ease 0s;
}
<div>
<form class="footer-contact-form" action="">
<fieldset class="footer-form-field">
<input id="name" class="input-value" name="name" type="text" autocomplete="off" required>
<label for="name">Navn*</label>
</fieldset>
<fieldset class="footer-form-field">
<input id="company" class="input-value" name="company" type="text" autocomplete="off">
<label for="company">Firma</label>
</fieldset>
<fieldset class="footer-form-field">
<input id="email" class="input-value" name="email" type="email" autocomplete="off" required>
<label for="email">E-mail*</label>
</fieldset>
<fieldset class="footer-form-field-txt">
<textarea id="message" class="input-value" name="message" required></textarea>
<label for="message">Besked*</label>
</fieldset>
<input class="footer-msg-send" value="Send Besked" type="submit">
</form>
<button class="fetch-deal">Send</button>
</div>
You can try something like this:
window.onload = function() {
var span1 = document.createElement("span");
span1.innerHTML = "test";
span1.className = "info";
span1.style.display = "none";
var span2 = document.createElement("span");
span2.innerHTML = "test";
span2.className = "info";
span2.style.display = "none";
var span3 = document.createElement("span");
span3.innerHTML = "test";
span3.className = "info";
span3.style.display = "none";
var username = document.getElementById("username");
username.parentNode.appendChild(span1);
var password = document.getElementById("password");
password.parentNode.appendChild(span2);
var email = document.getElementById("email");
email.parentNode.appendChild(span3);
username.onfocus = function() {
span1.className = "info";
span1.innerHTML = "infoMsg";
span1.style.display = "inline";
};
username.onblur = function() {
var alphanums = /^[a-z0-9A-Z]+$/;
if (username.value.match(alphanums)) {
span1.className = "ok";
span1.innerHTML = "Accepted";
} else {
span1.className = "error";
span1.innerHTML = "error";
}
if (username.value.length == 0) {
span1.className = "info";
span1.innerHTML = "infoMsg";
span1.style.display = "none";
}
};
password.onfocus = function() {
span2.innerHTML = "infoMsg";
span2.className = "info";
span2.style.display = "inline";
};
password.onblur = function() {
if (password.value.length < 6 && password.value.length > 0) {
span2.className = "error";
span2.innerHTML = "error";
}
if (password.value.length > 6) {
span2.className = "ok";
span2.innerHTML = "Accepted";
}
if (password.value.length == 0) {
span2.className = "info";
span2.innerHTML = "infoMsg";
span2.style.display = "none";
}
};
email.onfocus = function() {
span3.innerHTML = "infoMsg";
span3.className = "info";
span3.style.display = "inline";
};
email.onblur = function() {
var res = /^[^\s#]+#[^\s#]+\.[^\s#]+$/;
if (res.test(email.value)) {
span3.className = "ok";
span3.innerHTML = "Accepted";
} else {
span3.className = "error";
span3.innerHTML = "error";
}
if (email.value.length == 0) {
span3.className = "info";
span3.innerHTML = "infoMsg";
span3.style.display = "none";
}
};
};
All this is for this Html file:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>Form Validation</title>
<link rel="stylesheet" href="validate.css" />
<script src="validate.js"></script>
</head>
<body>
<h1>Form Validation</h1>
<form class="signup">
<table>
<tr>
<td><label for="username">Username:</label></td>
<td><input type="text" name="username" id="username" /></td>
</tr>
<tr>
<td><label for="password">Password:</label></td>
<td><input type="password" name="password" id="password" /></td>
</tr>
<tr>
<td><label for="email">Email:</label></td>
<td><input type="text" name="email" id="email" /></td>
</tr>
</table>
</form>
</body>
</html>

HTML Validation JS without using PHP

I made an application for people to fill out an application. I did some of the in form validation but now I want to ensure that when the user hits the submit button it checks to ensure that all field are filled out. I am stuck and cannot figure out the last part of this puzzle.
I believe all I need to make this work is a Application.js If someone could take a look at this and let me know what if anything I am missing. I did not include the CSS sheet or photos. Thank you for taking the time to help.
Here is the form. "Application.html"
<!DOCTYPE html>
<html>
<head>
<center><h1>AIFC Application Form</h1></center>
<script src="http://html5shiv.googlecode.com/svn/trunk/html5.js"></script>
<title>AIFC Application</title>
<meta charset="utf-8">
<meta name="author" content="Paul Skinner">
<link rel="stylesheet" type="text/css" href="Application.css" />
<style type="text/css">
</style>
<script src="Application.js"></script>
<script src="Application_Library.js"></script>
<script type="text/javascript">
function updateTotal() {
var basePrice = 50;
var optionsPrice = 0;
var memberPrice = 0;
function checkPayment() {
if (document.getElementById('payment0').checked) {
optionsPrice += 1;
}
if (document.getElementById('payment1').checked) {
optionsPrice += 9.6;
}
} // end of checking for payment
function checkJumper() {
if (document.getElementById('jumper0').checked) {
optionsPrice += 0;
}
if (document.getElementById('jumper1').checked) {
optionsPrice += 4.4;
}
} // end of checking for Jumper
function checkMembership() {
if (document.getElementById('membership').value == 'Basic') {
memberPrice += 75;
}
if (document.getElementById('membership').value == 'Silver') {
memberPrice += 125;
}
if (document.getElementById('membership').value == 'Gold') {
memberPrice += 150;
}
} // end of check membership function
checkPayment();
checkJumper();
checkMembership();
var totalPrice = basePrice + (optionsPrice * memberPrice);
document.getElementById('optionsPrice').innerHTML = optionsPrice;
document.getElementById('memberPrice').innerHTML = "$ " + memberPrice;
document.getElementById('totalPrice').innerHTML = "$ " + totalPrice;
}
</script>
</head>
<body>
<div id="top">
<nav class="horizontalNav">
<ul>
<li>Home</li>
<li>Application</li>
<li>Who We Are</li>
<li>Our Packages</li>
</ul>
</nav></div>
<section>
<table>
<tr style="white-space:nowrap; clear:both">
<td><img src="Images/girl punching.jpg" alt="Girl Punching" style=" float:left; height:200px" /></td>
<td><img src="images/fitness.jpg" alt="Weights" style=" float:right; height:200px; width:900px" /></td>
</tr>
</table>
</section>
<form action="#" method="get" name="application" id="application" >
<div id="form">
<fieldset>
<legend>Payment Type</legend><br>
<input type="radio" name="payment" id="payment0" value="payment0" onchange="updateTotal()"> Monthly membership <br>
<input type="radio" name="payment" id="payment1" value="payment1" onchange="updateTotal()"> Yearly membership <b>Big Savings!</b> <br><br>
</fieldset>
<fieldset>
<legend>Choose a Location</legend><br>
<input type="radio" name="jumper" id="jumper0" value="jumper0" onchange="updateTotal()"> Single Gym location
<input type="radio" name="jumper" id="jumper1" value="jumper1" onchange="updateTotal()"> All Locations <br><br>
</fieldset>
<fieldset>
<legend>Membership Type</legend><br>
<select name="membership" id="membership" onchange="updateTotal()">
<option value="Basic">Basic Membership ($75)</option>
<option value="Silver">Silver Membership ($125)</option>
<option value="Gold">Gold Membership ($150)</option><br>
</select>
</fieldset>
<fieldset>
<legend>Sex</legend><br>
<input type="radio" name="sex" value="male">Male<br>
<input type="radio" name="sex" value="female">Female<br>
</fieldset>
</div>
<div id="prices">
<table>
<tr><td>Membership Application Fee</td><td id="basePrice">$50</td></tr>
<tr><td>Option factor</td><td id="optionsPrice"></td></tr>
<tr><td>Membership</td><td id="memberPrice"></td></tr>
<tr><td>Total</td><td id="totalPrice"></td></tr>
</table>
</div>
<div id="info">
<fieldset>
<legend>Personal Information</legend>
<label for="first_name">First Name:</label>
<input type="text" id="firstname" name="first" required autofocus title="First Name" placeholder="First Name" />
<span id="first_name_error"> </span><br>
<label for="last_name">Last Name:</label>
<input type="text" id="lastname" name="last" required title="Last Name" placeholder="Last Name"/>
<span id="last_name_error"> </span><br>
<label for="address">Address:</label>
<input type="text" id="address" name="address" required title="Address" placeholder="Address"/>
<span id="address_error"> </span><br>
<label for="city">City:</label>
<input type="text" id="city" name="city" required title="City" placeholder="City"/>
<span id="city_error"> </span><br>
<label for="state">State:</label>
<input type="text" id="state" maxlength="2" name="State" required title="State" placeholder="State"/>
<span id="state_error"> </span><br>
<label for="zip_code">Zip Code:</label>
<input type="text" id="zip" name="zip" required title="Zip Code" placeholder="Zip Code" pattern="\d{5}([\-]\d{4})?"/>
<span id="zip_error"> </span><br>
<label for="phone_number">Phone Number:</label>
<input type="text" id="phone" name="phone" required title="Optional Phone Number 999-999-9999" placeholder="999-999-9999" pattern="\d{3}[\-]\d{3}[\-]\d{4}"/>
<span id="phone_error"> </span><br>
<label for="date_of_birth">Date of Birth:</label>
<input type="date" name="date" required title="MM-DD-YYYY"/>
<span id="date_error"> </span><br>
<label for="email">Email:</label>
<input type="email" id="email" name="email" required title="Email" placeholder="Email Address"/>
<span id="email_error"> </span>
<br>
</fieldset>
<br><br><center><input type="submit" id="submit" value="Become a Member"></center>
<br><center><input type="Reset" id="btn1" value="Reset Form"></center>
</div>
<br><br><div class="footer">
<address><center>
<b>American InterContinental Fitness Center</b> ☀
1578 Perseverance Lane ☀
Simple City, IL 60001
<br/> (630)432-1425
</address></center>
<br>
</div>
</form>
</body>
</html>
The next is the js: "Application_Library.js"
var $ = function (id) { return document.getElementById(id); }
var application = function () {
// All the different fields
this.field = [];
this.field["first_name"] = {};
this.field["last_name"] = {};
this.field["address"] = {};
this.field["city"] = {};
this.field["state"] = {};
this.field["zip"] = {};
this.field["phone"] = {};
this.field["date"] = {};
this.field["email"] = {};
// Field messages
this.field["state"].message = "Please use only a two letter State abbreviation.";
this.field["zip"].message = "Please use a 5 or 9 digit Zip Code";
this.field["phone"].message = "Please use 123-456-7890 format.";
this.field["email"].message = "Must be a vaild email address.";
// Error messages
this.field["email"].required = "Email is required";
this.field["confirmemail"].required = "Please confirm your email!";
this.field["confirmemail"].noMatch = "Emails do not Match!", "email";
this.field["first_name"].required = "First names are required.";
this.field["last_name"].required = "Last names are required.";
this.field["address"].required = "An Address is required";
this.field["city"].required = "A City is required";
this.field["state"].required = "A State is required";
this.field["state"].isState = "State invalid";
this.field["zip"].required = "A Zip code is required.";
this.field["zip"].isZip = "Zip code is invalid";
this.field["phone"].required = "A phone number is required";
this.field["phone"].isPhone = "The phone number is invalid";
this.field["date"].required = "Your date of birth is required";
}
Instead of writing your own javascript validation you can use the jQuery "form Validation Plug-in", which is an excellent tool for web pages to validate data entries at the client side using JavaScript. It's very simple to use.
Here is a sample tutorial
http://www.codeproject.com/Articles/213138/An-Example-to-Use-jQuery-Validation-Plugin
You should implement server side validation also for best security.
You can't just check data on JavaScript, you should also check it on server-side, because the client side is more accessible and user can change the JavaScript or even disable it, so the data would be invalidated.
You should write server-side validation too.
You forgot to show the Application.js file.
Also you can use HTML5 validation, without using any JavaScript:
http://www.sitepoint.com/html5-form-validation/

Categories

Resources