JavaScript success message after form submit/page re-load - javascript

I'm looking for a way to display a simple JS message/pop up when my form has been successfully submitted.
I tried doing this as an 'alert' but it stopped the 'action' from happening (page reloading) and just displayed the message instead.
If I could do this as a js alert after the action has happened and the page has reloaded this would be great but I'm open to suggestions...
Regards,
Marc
function validate() // Required Fields Validation
{
if (document.myForm.Name.value == "") {
alert("Please provide your name");
document.myForm.Name.focus();
return false;
}
if (document.myForm.Company.value == "") {
alert("Please provide your Company name");
document.myForm.Company.focus();
return false;
}
if (document.myForm.Email.value == "") {
alert("Please provide your Email address");
document.myForm.Email.focus();
return false;
}
if (document.myForm.Message.value == "") {
alert("Leave us a message");
document.myForm.Message.focus();
return false;
}
return (true);
}
function validateEmail() // Correct Email Format Validation
{
var emailID = document.myForm.Email.value;
atpos = emailID.indexOf("#");
dotpos = emailID.lastIndexOf(".");
if (atpos < 1 || (dotpos - atpos < 2)) {
alert("Please enter a valid Email address")
document.myForm.Email.focus();
return false;
}
return (true);
}
function nameLength() { // Max Character Validation
x = document.myForm
input = x.Name.value
if (input.length > 40) {
alert("The Name field cannot contain more than 40 characters")
return false
} else {
return true
}
}
function companyLength() {
x = document.myForm
input = x.Company.value
if (input.length > 50) {
alert("The Company field cannot contain more than 50 characters")
return false
} else {
return true
}
}
function emailLength() {
x = document.myForm
input = x.Email.value
if (input.length > 50) {
alert("The Email field cannot contain more than 50 characters")
return false
} else {
return true
}
}
function messageLength() {
x = document.myForm
input = x.Message.value
if (input.length > 300) {
alert("The Message field cannot contain more than 300 characters")
return false
} else {
return true
}
}
#contact-area {
width: 500px;
max-height: 200px;
margin-top: 0px;
float: left;
}
#contact-area input,
#contact-area textarea {
padding: 3px;
width: 520px;
font-family: 'Lato', sans-serif;
font-size: 14px;
margin: 0px 0px 0px 0px;
border: 1px solid #ccc;
}
#contact-area textarea {
height: 90px;
}
#contact-area textarea:focus,
#contact-area input:focus {
border: 1px solid #ffc423;
}
#contact-area input.submit-button {
width: 100px;
float: left;
background-color: #ffc423;
color: black;
margin-top: 13px;
cursor: pointer;
}
#contact-area input.submit-button:hover {
background-color: #002b51;
color: white;
}
label {
float: left;
text-align: left;
margin-right: 15px;
width: 100px;
padding-top: 10px;
padding-bottom: 5px;
font-size: 15px;
color: #ffc423;
font-weight: 700;
}
textarea {
resize: none;
}
<div id="contact-area">
<form method="post" action="contactengine.php" name="myForm" onsubmit="return !!(validate() & validateEmail() & nameLength() & companyLength() & emailLength() & messageLength())">
<label for="Name">Name:</label>
<input type="text" name="Name" id="Name">
<label for="Company">Company:</label>
<input type="text" name="Company" id="Company">
<label for="Email">Email:</label>
<input type="text" name="Email" id="Email">
<label for="Message">Message:</label>
<textarea name="Message" rows="20" cols="20" id="Message" title="Your message | max 300 characters"></textarea>
<input type="submit" name="submit" value="Submit" class="submit-button">
</form>
<div style="clear: both;"></div>
</div>

you can set a value to a querystring param and check this on your page to alert success:
Redirect function update:
if ($success){ print "<meta http-equiv=\"refresh\" content=\"0;URL=contact.html\?success=true">"; } else{ print "<meta http-equiv=\"refresh\" content=\"0;URL=error.htm\">"; }
Your page script:
you can have an on page load function to run the below:
var success = How can I get query string values in JavaScript? ;
if(success != ""){
alert(success); // javascript alert
}

Related

Redirect multi-step form

I not able to set up a redirect the form to a specific page/url after submitting the form.
I tried to put the following code
return window.location.href='index3.html';
right after
document.getElementById("regForm").submit();
but I got no data submitted, only redirect...
Can someone help please?
<!DOCTYPE html>
<html>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link href="https://fonts.googleapis.com/css?family=Raleway" rel="stylesheet">
<style>
* {
box-sizing: border-box;
}
body {
background-color: #f1f1f1;
}
#regForm {
background-color: #ffffff;
margin: 100px auto;
font-family: Raleway;
padding: 40px;
width: 70%;
min-width: 300px;
}
h1 {
text-align: center;
}
input {
padding: 10px;
width: 100%;
font-size: 17px;
font-family: Raleway;
border: 1px solid #aaaaaa;
}
/* Mark input boxes that gets an error on validation: */
input.invalid {
background-color: #ffdddd;
}
/* Hide all steps by default: */
.tab {
display: none;
}
button {
background-color: #04AA6D;
color: #ffffff;
border: none;
padding: 10px 20px;
font-size: 17px;
font-family: Raleway;
cursor: pointer;
}
button:hover {
opacity: 0.8;
}
#prevBtn {
background-color: #bbbbbb;
}
/* Make circles that indicate the steps of the form: */
.step {
height: 15px;
width: 15px;
margin: 0 2px;
background-color: #bbbbbb;
border: none;
border-radius: 50%;
display: inline-block;
opacity: 0.5;
}
.step.active {
opacity: 1;
}
/* Mark the steps that are finished and valid: */
.step.finish {
background-color: #04AA6D;
}
</style>
<body>
<form id="regForm" action="config.php">
<h1>Register:</h1>
<!-- One "tab" for each step in the form: -->
<div class="tab">Name:
<p><input placeholder="First name..." oninput="this.className = ''" name="fname"></p>
<p><input placeholder="Last name..." oninput="this.className = ''" name="lname"></p>
</div>
<div class="tab">Contact Info:
<p><input placeholder="E-mail..." oninput="this.className = ''" name="email"></p>
<p><input placeholder="Phone..." oninput="this.className = ''" name="phone"></p>
</div>
<div class="tab">Birthday:
<p><input placeholder="dd" oninput="this.className = ''" name="dd"></p>
<p><input placeholder="mm" oninput="this.className = ''" name="nn"></p>
<p><input placeholder="yyyy" oninput="this.className = ''" name="yyyy"></p>
</div>
<div class="tab">Login Info:
<p><input placeholder="Username..." oninput="this.className = ''" name="uname"></p>
<p><input placeholder="Password..." oninput="this.className = ''" name="pword" type="password"></p>
</div>
<div style="overflow:auto;">
<div style="float:right;">
<button type="button" id="prevBtn" onclick="nextPrev(-1)">Previous</button>
<button type="button" id="nextBtn" onclick="nextPrev(1)">Next</button>
</div>
</div>
<!-- Circles which indicates the steps of the form: -->
<div style="text-align:center;margin-top:40px;">
<span class="step"></span>
<span class="step"></span>
<span class="step"></span>
<span class="step"></span>
</div>
</form>
<script>
var currentTab = 0; // Current tab is set to be the first tab (0)
showTab(currentTab); // Display the current tab
function showTab(n) {
// This function will display the specified tab of the form...
var x = document.getElementsByClassName("tab");
x[n].style.display = "block";
//... and fix the Previous/Next buttons:
if (n == 0) {
document.getElementById("prevBtn").style.display = "none";
} else {
document.getElementById("prevBtn").style.display = "inline";
}
if (n == (x.length - 1)) {
document.getElementById("nextBtn").innerHTML = "Submit";
} else {
document.getElementById("nextBtn").innerHTML = "Next";
}
//... and run a function that will display the correct step indicator:
fixStepIndicator(n)
}
function nextPrev(n) {
// This function will figure out which tab to display
var x = document.getElementsByClassName("tab");
// Exit the function if any field in the current tab is invalid:
if (n == 1 && !validateForm()) return false;
// Hide the current tab:
x[currentTab].style.display = "none";
// Increase or decrease the current tab by 1:
currentTab = currentTab + n;
// if you have reached the end of the form...
if (currentTab >= x.length) {
// ... the form gets submitted:
document.getElementById("regForm").submit();
return false;
}
// Otherwise, display the correct tab:
showTab(currentTab);
}
function validateForm() {
// This function deals with validation of the form fields
var x, y, i, valid = true;
x = document.getElementsByClassName("tab");
y = x[currentTab].getElementsByTagName("input");
// A loop that checks every input field in the current tab:
for (i = 0; i < y.length; i++) {
// If a field is empty...
if (y[i].value == "") {
// add an "invalid" class to the field:
y[i].className += " invalid";
// and set the current valid status to false
valid = false;
}
}
// If the valid status is true, mark the step as finished and valid:
if (valid) {
document.getElementsByClassName("step")[currentTab].className += " finish";
}
return valid; // return the valid status
}
function fixStepIndicator(n) {
// This function removes the "active" class of all steps...
var i, x = document.getElementsByClassName("step");
for (i = 0; i < x.length; i++) {
x[i].className = x[i].className.replace(" active", "");
}
//... and adds the "active" class on the current step:
x[n].className += " active";
}
</script>
</body>
</html>
....``
It seems that this is part of the solution:
include "/config/config.php";
Reference this for more details.

Javascript Copy Function - This should work but isn't

Ok I have done this a million times. This is frustrating I cannot for the life of me figure out why this isn't copying my content from (notefield) I need a fresh pair of eyes to call me a dummy....
It's hit or miss it will work on 1 attempt then not again for 20 more tries. I have a feeling it has to do with something I am doing that I am overlooking.
my CopyReset() function is just failing 90% of the time and I have made this function 10000 times before no issue...
HTML (With copy function)
<html>
<head>
<title> Tech Helper </title>
<link rel="stylesheet" type="text/css" href="css\layout.css">
<script src="scripts\newTicket.js"></script>
</head>
<header>
<div id='header' class='header'>
<div id='logo' class='logo' align='right'>
<img src="redactedlink" class='banner'></img>
</div>
<div class='headtable'>
<table id='headtable'>
<tr>
<th>Technician Name: <input type="text" id='techName' value=""> </th>
</tr>
</table>
</div>
</div>
</header>
<body onload="LoadScript()">
<div id='container' class='container'>
<table id='containertable' class='tabcontainer'>
<tr>
<td class='tableft'><div id='navmenu'></div></td>
<td class='tabright'><table id='content'></table></th>
</tr>
</table>
</div>
</body>
<div id='footer' class='footer'>
<table id='foottable' class='foottable'>
<tr>
<th> Footer </th>
</tr>
</table>
</div>
<textarea id="notefield" class="hiddentext"></textarea>
<script>
function CopyReset() {
var target = document.getElementById('notefield');
target.select();
document.execCommand('copy');
//alert("Cancellation Notes Copied");
document.getElementById("content").innerHTML = "";
//document.getElementById("notefield").value = "";
}
</script>
</html>
Javascript newTicket.js
function LoadScript() {
document.getElementById('navmenu').innerHTML = "<input type='button' onclick='NewTicket()'
class='navButton' value='New Ticket' id='newTicket'>";
}
var reached = "false";
function NewTicket() {
var incident = prompt("Enter Incident Number");
var c = document.getElementById("content");
if ( incident == null || incident.length != 15 ) {
alert("Invalid Incident Number Entered, Please enter a valid Incident number!");
}
else if ( incident != null && incident.length == 15 ) {
c.innerHTML = "<tr> <td colspan='100%'> Incident: <input type='text' id='incField' value=''
class='readonlyfield' readonly></td></td>";
c.innerHTML += "<tr id='contactInfo1'> <th colspan='2'>Please Select Contact Method:</th></tr><tr
id='contactInfo2'><td colspan='2 class='td1'><div id='contactInfo' align='center'> Phone: <input
type='radio' onclick='phoneContact()' name='contactType' id='phone'> Skype: <input type='radio'
onclick='skypeContact()' name='contactType' id='skype'></div></td></tr>";
document.getElementById('incField').value = incident;
document.getElementById('navmenu').innerHTML = "";
document.getElementById('navmenu').innerHTML = "<input type='button' class='navButton' value='Cancel
Ticket' onclick='CancelTicket()' id='endTicket'>";
}
}
function phoneContact() {
var numberUsed = prompt('Please Enter the number you called the user at');
if ( numberUsed == null ) {
alert('Must enter a Phone Number');
}
else if (numberUsed != null) {
document.getElementById('notefield').value += "Reached user at: " + numberUsed + "\n";
reached = "true";
document.getElementById('contactInfo1').innerHTML = "";
document.getElementById('contactInfo2').innerHTML = "";
}
}
function skypeContact() {
var skypeLog = prompt('Please Contact Log to begin');
if ( skypeLog == null ) {
alert('Must Provide Contact Log!');
}
else if (skypeLog != null) {
document.getElementById('notefield').value += "Reached User via Skype: " + skypeLog + "\n";
reached = "true";
document.getElementById('contactInfo1').innerHTML = "";
document.getElementById('contactInfo2').innerHTML = "";
}
}
function CancelTicket() {
if (reached == "false" ) {
alert('Canno Cancel Ticket Without Contact');
}
else if (reached == "true" ) {
var reason = prompt("Reason for cancelling ticket: ");
if (reason == null) {
alert('Cancel Reason cannot be blank!');
}
else if (reason != null) {
document.getElementById('navmenu').innerHTML = "<input type='button'
class='navButton'
onclick='NewTicket()' value='New Ticket' id='newTicket'>";
document.getElementById('notefield').value += "Ticket Cancelled, Reason: " + reason;
CopyReset();
}
}
}
And for SNG's CSS layout.css
.header {
border-radius: 10px 10px 0px 0px;
background-color:blue;
width: auto;
margin-left: 20px;
margin-right: 20px;
margin-top:20px;
height: 80px;
position:relative;
}
.headtable {
position:absolute;
margin: 20px 10px 0px 10px;
vertical-align: text-bottom;
}
.logo {
width:350px;
padding-top:10px;
padding-right:10px;
float:right;
}
.td1 {
text-align: right;
}
.banner {
}
.hiddentext {
opacity:100%;
}
.incbox {
float:left;
}
.readonlyfield {
background-color: #eee;
}
.navButton {
width: 100%;
height:25px;
border-radius: 5px 5px 5px 5px;
border-color:blue;
}
.navButton:Hover {
border-radius: 1px 1px 1px 1px;
border-color:black;
background:lightblue;
opacity: 96%;
}
.container {
background-color:green;
width: auto;
height: 600px;
position:relative;
margin-left: 20px;
margin-right: 20px;
}
.tabcontainer {
width: 100%;
height: 600px;
}
.tableft {
vertical-align: text-top;
background-color: yellow;
width:15%;;
}
.tabright {
vertical-align: text-top;
background-color: pink;
}
.footer {
position:relative;
border-radius: 0px 0px 10px 10px;
bottom: 0px;
background-color:red;
width: auto;
height: 80px;
margin-left: 20px;
margin-right: 20px;
margin-bottom: 20px;
}
Ok, here I've bug fixed a little your JS code, especially some line breaks within single quotes where some html tags is placed... Also added block to run JS only after DOM loaded, don't know is it the case, but in sandbox here it gives error without it. So check demo below, in my case text pasted to textarea and copied to clipboard when you cancel ticket
function LoadScript() {
document.getElementById('navmenu').innerHTML = "<input type='button' onclick='NewTicket()' class='navButton' value='New Ticket' id='newTicket'>";
}
var reached = "false";
function NewTicket() {
var incident = prompt("Enter Incident Number");
var c = document.getElementById("content");
if ( incident == null || incident.length != 15 ) {
alert("Invalid Incident Number Entered, Please enter a valid Incident number!");
}
else if ( incident != null && incident.length == 15 ) {
c.innerHTML = "<tr> <td colspan='100%'> Incident: <input type='text' id='incField' value='' class='readonlyfield' readonly></td></td>";
c.innerHTML += "<tr id='contactInfo1'> <th colspan='2'>Please Select Contact Method:</th></tr><tr id='contactInfo2'><td colspan='2 class='td1'><div id='contactInfo' align='center'> Phone: <input type='radio' onclick='phoneContact()' name='contactType' id='phone'> Skype: <input type='radio' onclick='skypeContact()' name='contactType' id='skype'></div></td></tr>";
document.getElementById('incField').value = incident;
document.getElementById('navmenu').innerHTML = "";
document.getElementById('navmenu').innerHTML = "<input type='button' class='navButton' value='Cancel Ticket' onclick='CancelTicket()' id='endTicket'>";
}
}
function phoneContact() {
var numberUsed = prompt('Please Enter the number you called the user at');
if ( numberUsed == null ) {
alert('Must enter a Phone Number');
}
else if (numberUsed != null) {
document.getElementById('notefield').value += "Reached user at: " + numberUsed + "\n";
reached = "true";
document.getElementById('contactInfo1').innerHTML = "";
document.getElementById('contactInfo2').innerHTML = "";
}
}
function skypeContact() {
var skypeLog = prompt('Please Contact Log to begin');
if ( skypeLog == null ) {
alert('Must Provide Contact Log!');
}
else if (skypeLog != null) {
document.getElementById('notefield').value += "Reached User via Skype: " + skypeLog + "\n";
reached = "true";
document.getElementById('contactInfo1').innerHTML = "";
document.getElementById('contactInfo2').innerHTML = "";
}
}
function CancelTicket() {
if (reached == "false" ) {
alert('Canno Cancel Ticket Without Contact');
}
else if (reached == "true" ) {
var reason = prompt("Reason for cancelling ticket: ");
if (reason == null) {
alert('Cancel Reason cannot be blank!');
}
else if (reason != null) {
document.getElementById('navmenu').innerHTML = "<input type='button' class='navButton' onclick='NewTicket()' value='New Ticket' id='newTicket'>";
document.getElementById('notefield').value += "Ticket Cancelled, Reason: " + reason;
CopyReset();
}
}
}
.header {
border-radius: 10px 10px 0px 0px;
background-color:blue;
width: auto;
margin-left: 20px;
margin-right: 20px;
margin-top:20px;
height: 80px;
position:relative;
}
.headtable {
position:absolute;
margin: 20px 10px 0px 10px;
vertical-align: text-bottom;
}
.logo {
width:350px;
padding-top:10px;
padding-right:10px;
float:right;
}
.td1 {
text-align: right;
}
.banner {
}
.hiddentext {
opacity:100%;
}
.incbox {
float:left;
}
.readonlyfield {
background-color: #eee;
}
.navButton {
width: 100%;
height:25px;
border-radius: 5px 5px 5px 5px;
border-color:blue;
}
.navButton:Hover {
border-radius: 1px 1px 1px 1px;
border-color:black;
background:lightblue;
opacity: 96%;
}
.container {
background-color:green;
width: auto;
height: 600px;
position:relative;
margin-left: 20px;
margin-right: 20px;
}
.tabcontainer {
width: 100%;
height: 600px;
}
.tableft {
vertical-align: text-top;
background-color: yellow;
width:15%;;
}
.tabright {
vertical-align: text-top;
background-color: pink;
}
.footer {
position:relative;
border-radius: 0px 0px 10px 10px;
bottom: 0px;
background-color:red;
width: auto;
height: 80px;
margin-left: 20px;
margin-right: 20px;
margin-bottom: 20px;
}
<html>
<head>
<title> Tech Helper </title>
<link rel="stylesheet" type="text/css" href="css\layout.css">
<script src="scripts\newTicket.js"></script>
</head>
<header>
<div id='header' class='header'>
<div id='logo' class='logo' align='right'>
<img src="redactedlink" class='banner'></img>
</div>
<div class='headtable'>
<table id='headtable'>
<tr>
<th>Technician Name: <input type="text" id='techName' value=""> </th>
</tr>
</table>
</div>
</div>
</header>
<body onload="">
<div id='container' class='container'>
<table id='containertable' class='tabcontainer'>
<tr>
<td class='tableft'><div id='navmenu'></div></td>
<td class='tabright'><table id='content'></table></th>
</tr>
</table>
</div>
</body>
<div id='footer' class='footer'>
<table id='foottable' class='foottable'>
<tr>
<th> Footer </th>
</tr>
</table>
</div>
<textarea id="notefield" class="hiddentext"></textarea>
<script>
function CopyReset() {
var target = document.getElementById('notefield');
target.select();
document.execCommand('copy');
//alert("Cancellation Notes Copied");
document.getElementById("content").innerHTML = "";
//document.getElementById("notefield").value = "";
}
// Wait for DOM loads
document.addEventListener("DOMContentLoaded", function() {
LoadScript()
});
</script>
</html>
Figured it out without removing the buttons
newTicet.js
function LoadScript() {
document.getElementById('navmenu').innerHTML = "<input type='button' onclick='NewTicket()' class = 'navButton'value = 'New Ticket'id = 'newTicket' > ";
}
reached = 0;
function NewTicket() {
var incident = prompt("Enter Incident Number");
var c = document.getElementById("content");
if (incident == null || incident.length != 15) {
alert("Invalid Incident Number Entered, Please enter a valid Incident number!");
}
else if (incident != null && incident.length == 15) {
c.innerHTML = "<tr> <td colspan='100%'> Incident: <input type='text' id='incField' value='' class = 'readonlyfield' readonly> </td></td> ";
c.innerHTML += "<tr id='contactInfo1'> <th colspan='2'>Please Select Contact Method:</th></tr><tr id='contactInfo2'> <td colspan = '2 class='td1'><div id='contactInfo' align='center'> Phone: <input type='radio' onclick='phoneContact()' name='contactType'id = 'phone' > Skype: <input type='radio' onclick = 'skypeContact()' name = 'contactType' id = 'skype' > </div></td > </tr>";
document.getElementById('incField').value = incident;
document.getElementById('navmenu').innerHTML = "";
document.getElementById('navmenu').innerHTML = "<input type='button' class='navButton' value='Cancel Ticket' onclick='CancelTicket()' id='endTicket'>";
}
}
function phoneContact() {
var numberUsed = prompt('Please Enter the number you called the user at');
if (numberUsed == null) {
alert('Must enter a Phone Number');
}
else if (numberUsed != null) {
document.getElementById('notefield').value += "Reached user at: " + numberUsed + "\n";
reached = 1;
document.getElementById('contactInfo1').innerHTML = "";
document.getElementById('contactInfo2').innerHTML = "";
}
}
function skypeContact() {
var skypeLog = prompt('Please Contact Log to begin');
if (skypeLog == null) {
alert('Must Provide Contact Log!');
}
else if (skypeLog != null) {
document.getElementById('notefield').value += "Reached User via Skype: " + skypeLog + "\n";
reached = 1;
document.getElementById('contactInfo1').innerHTML = "";
document.getElementById('contactInfo2').innerHTML = "";
}
}
function CancelTicket() {
if (Boolean(reached) == false) {
alert("Cannot Cancel Ticket Without Contact");
}
else if (Boolean(reached) == true) {
var reason = prompt("Reason for cancelling ticket: ");
}
if (reason == null) {
alert("Cancel Reason cannot be blank!");
}
else if (reason != null) {
document.getElementById('navmenu').innerHTML = "<input type='button' class='navButton' onclick='NewTicket()' value='New Ticket' id='newTicket'>";
document.getElementById('notefield').value += "Ticket Cancelled, Reason: " + reason;
CopyReset();
}
}
function CopyReset() {
var target = document.getElementById('notefield');
target.select();
document.execCommand('copy');
alert("Cancellation Notes Copied");
document.getElementById("content").innerHTML = "";
document.getElementById("notefield").value = "";
}

How to check all conditions before executing aftermath

I am working on a live validation function. The problem is that the aftermath of the conditions in the function executes executes before the last part is met. The entry validation indicator should not turn green until the conditions are met, however this is not the case.
The indicator turns green after the third condition is met. It should not, until all conditions are met. Any suggestions on how I can solve this problem.
My code looks like below.
$(function() {
// Pre-define extensions
var xTension = ".com .net .edu";
$("input").keyup(function() {
// Check the position of "#" symbol
var firstLetter = $(this).val().slice(0, 1);
var lastLetter = $(this).val().slice(-1);
var userXs = "No";
// User provided extension
var userX = $(this).val();
userX = userX.substr(userX.indexOf(".") + 0);
if (xTension.indexOf(userX) > -1) {
if (userX != "") {
userXs = "Yes";
} else {
userXs = "No";
}
} else {
userXs = "No";
};
if ($(this).val().indexOf("#") > -1 && (firstLetter != "#") && (lastLetter != "#") && (userXs != "No")) {
$("#input-status").removeClass("red").addClass("green");
} else {
$("#input-status").removeClass("green").addClass("red");
}
});
});
.rack {
width: 250px;
margin: 0 auto;
}
#input-status {
width: 1px;
height: 3px;
with: 0;
display: inline-block;
transition: all 2s;
}
input {
width: 230px;
height: 30px;
text-align: center;
}
#input-status.green,
#input-status.red {
width: 235px;
background: darkGreen;
transition: all 2s;
}
#input-status.red {
background: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="rack">
<h1>Live Validat.ion</h1>
<input type="text" placeholder="Enter email address">
<div id="input-status">
</div>
</div>
Make xTension an array, not a string. If the user types user#foo.c, userX will be .c and this will be matched by indexOf() with the string, since there's nothing that forces it to match whole words. When you do this, you no longer need to check whether userX is an empty string.
I've made a few other simplifications to the code:
Instead of getting the first and last characters, just test the position of # against appropriate limits.
No need for + 0 after indexOf().
Don't keep calling $(this).val(), put it in a variable.
User a boolean variable for userXs.
$(function() {
// Pre-define extensions
var xTension = [".com", ".net", ".edu"];
$("input").keyup(function() {
var val = $(this).val();
// User provided extension
userX = val.substr(val.indexOf("."));
userXs = xTension.indexOf(userX) > -1;
atPos = val.indexOf("#");
if (atPos > 0 && atPos < val.length - 1 && userXs) {
$("#input-status").removeClass("red").addClass("green");
} else {
$("#input-status").removeClass("green").addClass("red");
}
});
});
.rack {
width: 250px;
margin: 0 auto;
}
#input-status {
width: 1px;
height: 3px;
with: 0;
display: inline-block;
transition: all 2s;
}
input {
width: 230px;
height: 30px;
text-align: center;
}
#input-status.green,
#input-status.red {
width: 235px;
background: darkGreen;
transition: all 2s;
}
#input-status.red {
background: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="rack">
<h1>Live Validat.ion</h1>
<input type="text" placeholder="Enter email address">
<div id="input-status">
</div>
</div>

Multiple toggles using javaScript not jquery

I'm currently trying to make a page with an overlay that toggles once the form is correctly filled out then submitted. Once the first form is submitted it should take you to another. Both forms are in the html already, first overlay works but second does not.
function formValidator() {
var firstname = document.getElementById('firstname');
var lastname = document.getElementById('lastname');
var email = document.getElementById('email');
var phone = document.getElementById('phone');
// Check each input in the order that it appears in the form!
if (notEmpty(firstname, "Cannot leave First Name empty")) {
if (notEmpty(lastname, "Cannot leave Last Name empty")) {
if (notEmpty(phone, "Cannot leave Phone # empty")) {
if (notEmpty(email, "Cannot leave Email empty")) {
if (isAlphabet(firstname, "Please enter only letters for your first name")) {
if (isAlphabet(lastname, "Please enter only letters for your last name")) {
if (phoneValidator(phone, "Numbers only for phone # in the xxx-xxx-xxxx format")) {
if (emailValidator(email, "Please enter a valid email address")) {
return true;
}
}
}
}
}
}
}
}
return false;
}
function notEmpty(elem, helperMsg){
if(elem.value.length == 0){
alert(helperMsg);
elem.focus(); // set the focus to this input
return false;
}
return true;
}
function isAlphabet(elem, helperMsg){
var alphaExp = /^[a-zA-Z]+$/;
if(elem.value.match(alphaExp)){
return true;
}else{
alert(helperMsg);
elem.focus();
return false;
}
}
function phoneValidator(elem, helperMsg){
var alphaExp = /^\(?(\d{3})\)?[- ]?(\d{3})[- ]?(\d{4})$/;
if(elem.value.match(alphaExp)){
return true;
}else{
alert(helperMsg);
elem.focus();
return false;
}
}
function emailValidator(elem, helperMsg){
var emailExp = /^[\w\-\.\+]+\#[a-zA-Z0-9\.\-]+\.[a-zA-z0-9]{2,4}$/;
if(elem.value.match(emailExp)){
return true;
}else{
alert(helperMsg);
elem.focus();
return false;
}
}
function formValidator2(){
var dropdown1 = document.getElementById('selection').value;
var dropdown2 = document.getElementById('selection2').value;
var dropdown3 = document.getElementById('selection3').value;
var dropdown4 = document.getElementById('selection4').value;
var dropdown5 = document.getElementById('selection5').value;
if(dropdown1 == ""){
alert("Please make a selection (Job Category)");
return false;
}
if(dropdown2 == ""){
alert("Please make a selection (Job Title)");
return false;
}
if(dropdown3 == ""){
alert("Please make a selection (Highest Education Level)");
return false;
}
if(dropdown4 == ""){
alert("Please make a selection (High School Graduation Year)");
return false;
}
if(dropdown5 == ""){
alert("Please make a selection (Further Education)");
return false;
}else{
return true;
}
}
/*I am currently unable to toggle from box1 to box2*/
function toggleOverlay(){
var overlay = document.getElementById('overlay');
var specialBox = document.getElementById('Box1');
var specialBox1 = document.getElementById('Box2');
overlay.style.opacity = .7;
if(overlay.style.display == "block"){
overlay.style.display = "none";
specialBox.style.display = "none";
specialBox1.style.display = "none";
} else if (specialBox.style.display == "block" && overlay.style.display == "block") {
overlay.style.display = "block";
specialBox1.style.display = "block";
specialBox.style.display = "none";
} else {
overlay.style.display = "block";
specialBox.style.display = "block";
}
}
body{
height: 100vmin;
margin-top: 0;
}
.header {
background-color: #F1F5FA;
}
.header p:first-child {
color: #4AC3E8;
margin: 0;
padding-top: 2%;
text-align: center;
font-size: 2.5vmin;
}
.header p:nth-child(2) {
color: #D3D3D8;
margin-top: 1%;
text-align: center;
padding-bottom: 2%;
}
.dark-blue {
color: #0080A4;
}
.text {
color: #00479B;
font-size: 3vmin;
}
.text2 {
color: #00479B;
font-size: 2vmin;
}
.input {
width: 30%;
margin-left: 3%;
height: 30px;
}
.spacing2 {
margin-left: 24%;
}
.spacing3 {
margin-left: 28%;
}
.button {
display: block;
margin-left: auto;
margin-right: auto;
margin-top: 5%;
width: 35%;
background-color: #008BBF;
color: white;
border-radius: 5px;
height: 50px;
font-weight: bold;
}
#main p {
color: #C6C8c8;
padding-left: 15%;
padding-right: 15%;
font-size: 1.5vmin;
margin-top: 5%;
}
.underline {
text-decoration: underline;
}
#skip {
background-color: #D7D7D7;
border-radius: 5px;
display: block;
margin-left: auto;
margin-right: auto;
width: 35%;
height: 30px;
color: #585858;
font-weight: bold;
margin-top: 3%;
}
form {
text-align: center;
}
form p {
font-size: 2.5vmin;
}
select {
width: 25%;
}
#paragraph {
color: #c6c8c8;
padding-left: 15%;
padding-right: 15%;
}
div#overlay {
display: none;
z-index: 2;
background: #000;
position: fixed;
width: 100%;
height: 100%;
top: 0;
left: 0;
text-align: center;
}
div#Box1 {
display: none;
position: fixed;
z-index: 3;
width: 70%;
height: 85%;
background: #FFF;
color: #000;
margin-left: 15%;
margin-top: 5%;
margin-bottom: 5%;
top: 0;
}
div#wrapper {
height: 1000px;
text-align: center;
margin-top: 10%;
}
div#Box2 {
display: none;
position: fixed;
z-index: 3;
width: 70%;
height: 85%;
background: #FFF;
color: #000;
margin-left: 15%;
margin-top: 5%;
margin-bottom: 5%;
top: 0;
}
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" type="text/css" href="interview.css">
<script type="text/javascript" src="validation.js"></script>
</head>
<body>
<!-- Start Overlay -->
<div id="overlay"></div>
<!-- End Overlay -->
<!-- Start Special Centered Box -->
<div id="Box1">
<div class="header">
<p>WE FOUND <span class="dark-blue">ALL JOBS</span> NEAR 94536</p>
<p>To get started, enter your contact information to see qualified job offers in your area.</p>
</div>
<div id="main">
<form id="form" onsubmit='return formValidator()'>
<span class="text spacing">First Name:</span><span class="text spacing2">Last Name:</span><br>
<input type="text" id="firstname" class="input">
<input type="text" id="lastname" class="input"> <br>
<span class="text spacing">Phone:</span><span class="text spacing3">Email:</span><br>
<input type="text" id="phone" class="input">
<input type="text" id="email" class="input"><br>
<button type="submit" form="form" class="button" onsubmit="toggleOverlay()">SUBMIT</button>
</form>
<!--Normally terms and conditions would be a link instead of underline below-->
<p>By submitting my information, I agree to the <span class="underline">Terms and Conditions</span> and <span class="underline">Privacy Policy.</span></p>
<p>By clicking continue, I consent to be contacted regarding education opportunities at the phone number provided,
including mobile number, using an automated telephone dialing system. I may be contacted by 2 of the following:
College Achieve, College Complete, Education Bridge, US News Univ. Connection, Career Advisor, or preferred partners.
Consent is not required as a condition of using this service.</p>
<button type="submit" id='skip' onmousedown="toggleOverlay()">SKIP TO RESULTS</button>
</div>
</div>
<div id="Box2">
<div class="header">
<p>While we generate your <span class="dark-blue">ALL JOBS</span> search results, please complete your profile for a more targeted search......</p>
<p>Your ALL JOBS will display shortly.</p>
</div>
<div>
<form id="form2" onsubmit='return formValidator2()'>
<p class="text2">Job Category</p>
<select id="selection">
<option value=""></option>
<option>Govt Services</option>
<option>Food</option>
<option>Entertainment</option>
<option>Internet</option>
</select>
<p class="text2">Job Title</p>
<select id="selection2">
<option value=""></option>
<option>Mechanic</option>
<option>Web Developer</option>
<option>Server</option>
<option>Accountant</option>
</select>
<p class="text2">Highest Education Level?</p>
<select id="selection3">
<option value=""></option>
<option>High School</option>
<option>Some College</option>
<option>College</option>
<option>Masters</option>
</select>
<p class="text2">High School Graduation Year?</p>
<select id="selection4">
<option value=""></option>
<option>2000</option>
<option>1999</option>
<option>1998</option>
<option>1997</option>
<option>1996</option>
<option>1995</option>
<option>1994</option>
<option>1993</option>
</select>
<p class="text2">Are You Interested in Furthering Your Education?</p>
<select id="selection5">
<option value=""></option>
<option>Yes</option>
<option>No</option>
</select> <br>
<button type="submit" form="form2" class="button">CONTINUE</button>
</form>
<p id="paragraph">
By clicking continue, I consent to be contacted regarding education opportunities at the phone number provided,
including mobile number, using an automated telephone dialing system. I may be contacted by 2 of the following:
College Achieve, College Complete, Education Bridge, US News Univ. Connection, Career Advisor, or preferred partners.
Consent is not required as a condition of using this service.
</p>
</div>
</div>
<!-- Start Special Centered Box -->
<!-- Start Normal Page Content -->
<div id="wrapper">
<button onmousedown="toggleOverlay()">Apply Overlay</button>
</div>
<!-- End Normal Page Content -->
</body>
</html>
You have couple of places to correct.
Form submission triggers to reload the whole page (equals start
over).
After first form submission all boxes are hidden, so you can not
check their display attributes.
To correct the first issue always return false but call overlay before that:
function formValidator() {
var firstname = document.getElementById('firstname');
var lastname = document.getElementById('lastname');
var email = document.getElementById('email');
var phone = document.getElementById('phone');
// Check each input in the order that it appears in the form!
if (notEmpty(firstname, "Cannot leave First Name empty")) {
if (notEmpty(lastname, "Cannot leave Last Name empty")) {
if (notEmpty(phone, "Cannot leave Phone # empty")) {
if (notEmpty(email, "Cannot leave Email empty")) {
if (isAlphabet(firstname, "Please enter only letters for your first name")) {
if (isAlphabet(lastname, "Please enter only letters for your last name")) {
if (phoneValidator(phone, "Numbers only for phone # in the xxx-xxx-xxxx format")) {
if (emailValidator(email, "Please enter a valid email address")) {
toggleOverlay();
}
}
}
}
}
}
}
}
return false;
}
To correct second issue I have introduced the counter, on how many times the ApplyOverlay button was clicked. Based on its value, different form is displayed:
/*I am currently unable to toggle from box1 to box2*/
// This should fix it
var counter = 0;
function toggleOverlay(){
var overlay = document.getElementById('overlay');
var specialBox = document.getElementById('Box1');
var specialBox1 = document.getElementById('Box2');
overlay.style.opacity = .7;
if (counter==1) {
overlay.style.display = "none";
specialBox.style.display = "none";
specialBox1.style.display = "none";
} else if (counter==2) {
overlay.style.display = "block";
specialBox1.style.display = "block";
specialBox.style.display = "none";
} else {
overlay.style.display = "block";
specialBox.style.display = "block";
}
counter++;
}

validate and submit form via jquery ajax

I have below jquery code for validation and html code for form. I would like to validate the form and then submit. Both the pieces of code are working properly ie for validation and for submit. The thing is how should I combine the code so that it can validate the form first and then submit it.
To get this done i did several changes to your script.
$(document).ready(function(){
//global vars
var form = $("#subscribeForm");
var name = $("#name");
var email = $("#email");
var nameInfo = $("#nameInfo");
var emailInfo = $("#emailInfo");
//On blur
name.blur(validateName);
email.blur(validateEmail);
//On key press
name.keyup(validateName);
var value = $('#button input').val();
var name1 = $('#button input').attr('name');
$('#button input').remove();
$('#button').html('<a href="#" class="cssSubmitButton" rel=' + name1 + '>' + value + '</a>');
//validation functions
function validateEmail(){
//testing regular expression
var a = $("#email").val();
var filter = /^(([^<>()[\]\\.,;:\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 it's valid email
if(filter.test(a)){
email.removeClass("error");
emailInfo.text("Valid E-mail please, you will need it to log in!");
emailInfo.removeClass("error");
return true;
}
//if it's NOT valid
else{
email.addClass("error");
emailInfo.text("Type a valid e-mail please :P");
emailInfo.addClass("error");
return false;
}
}
function validateName(){
//if it's NOT valid
if(name.val().length < 4){
name.addClass("error");
nameInfo.text("We want names with more than 3 letters!");
nameInfo.addClass("error");
return false;
}
//if it's valid
else{
name.removeClass("error");
nameInfo.text("What's your name?");
nameInfo.removeClass("error");
return true;
}
}
$('#button').on('click','a',function () {
var isValid = false;
if(validateName() & validateEmail())
isValid = true
else
isValid = false;
//You can use default form submission or with the ajax call below
//In this example, I'm using a dummy php call so that you can see the loading animation
//$('form[name=' + $(this).attr('rel') + ']').submit();
if(isValid)
{
var link = $(this);
$.ajax({
url : 'load.php',
data: '',
type: 'GET',
cache: 'false',
beforeSend: function () {
link.addClass('loading');
},
success: function () {
link.removeClass('loading');
$('#button').css('display','none');
$('#success').css('display','block');
alert('Submitted');
},
error: function() {
}
});
}
});
});
and added some id's to your html.
<form method="post" action="" id="subscribeForm" name="subscribeForm">
<fieldset>
<label>Name: </label><input type="text" class="effect" name="name" id="name">
<span id="nameInfo">What's your name?</span>
</fieldset>
<fieldset>
<label>Email: </label><input type="text" class="effect" name="email" id="email">
<span id="emailInfo">Valid E-mail please, you will need it to log in!</span>
</fieldset>
<div id="button">
<input type="submit" value="Subscribe" name="subscribeForm"/>
</div>
<div id="success">
<strong>Data Saved Successfully.</strong>
</div>
Thanks for your answers but even I got my code working. The below is the working code.
Java Script
<script type="text/javascript">
/*<![CDATA[*/
$(document).ready(function () {
var value = $('#button input').val();
var name = $('#button input').attr('name');
$('#button input').remove();
$('#button').html('<a href="#" class="cssSubmitButton" rel=' + name + '>' + value + '</a>');
//global vars
var form = $("#customForm");
var name = $("#name");
var nameInfo = $("#nameInfo");
var email = $("#email");
var emailInfo = $("#emailInfo");
//On blur
name.blur(validateName);
email.blur(validateEmail);
//On key press
name.keyup(validateName);
//On Submitting
$('#button a').live('click', function () {
var link = $(this);
if(validateName() & validateEmail())
{
var link = $(this);
$.ajax({
url : 'load.php',
data: '',
type: 'GET',
cache: 'false',
beforeSend: function () {
link.addClass('loading');
},
success: function () {
link.removeClass('loading');
$('#button').css('display','none');
$('#success').css('display','block');
alert('Submitted');
},
error: function() {
}
});
return true
}
else
{
return false;
}
});
//validation functions
function validateEmail(){
//testing regular expression
var a = $("#email").val();
var filter = /^[a-zA-Z0-9]+[a-zA-Z0-9_.-]+[a-zA-Z0-9_-]+#[a-zA-Z0-9]+[a-zA-Z0-9.-]+[a-zA-Z0-9]+.[a-z]{2,4}$/;
//if it's valid email
if(filter.test(a)){
email.removeClass("error");
emailInfo.text("Valid E-mail please, you will need it to log in!");
emailInfo.removeClass("error");
return true;
}
//if it's NOT valid
else{
email.addClass("error");
emailInfo.text("Stop cowboy! Type a valid e-mail please :P");
emailInfo.addClass("error");
return false;
}
}
function validateName(){
//if it's NOT valid
if(name.val().length < 4){
name.addClass("error");
nameInfo.text("We want names with more than 3 letters!");
nameInfo.addClass("error");
return false;
}
//if it's valid
else{
name.removeClass("error");
nameInfo.text("What's your name?");
nameInfo.removeClass("error");
return true;
}
}
});
/*]]>*/
</script>
CSS Script.
<style type="text/css">
body {
font-family: arial;
font-size:12px;
margin:10px;
text-align:center;
}
form {
margin:0 auto;
text-align:left;
width:270px;
border:1px solid #ccc;
padding:15px;
background:#fff;
border-radius: 10px;
-moz-border-radius: 10px;
-webkit-border-radius: 10px;
box-shadow: 0 0 4px #ccc;
-webkit-box-shadow: 0 0 4px #ccc;
-moz-box-shadow: 0 0 4px #ccc;
}
fieldset {
overflow:hidden;
border:0;
height:30px;
margin:3px 0;
}
fieldset label {
display:block;
width:50px;
float:left;
font-weight:700;
color:#666;
line-height:2.2em;
}
fieldset input {
float:left;
border:1px solid #ccc;
height: 20px;
padding:3px;
width:190px;
font-size:12px;
}
#button {
margin-top:10px;
padding-right:20px;
text-align:right;
}
#button input {
margin:0 auto;
}
a.cssSubmitButton {
font-size: 12px;
background: #fff no-repeat 4px 5px;
display: inline-block;
padding: 5px 20px 6px;
color: #333;
border:1px solid #ccc;
text-decoration: none;
font-weight: bold;
line-height: 1.2em;
border-radius: 15px;
-moz-border-radius: 15px;
-webkit-border-radius: 15px;
-moz-box-shadow: 0 1px 3px #999;
-webkit-box-shadow: 0 1px 3px #999;
position: relative;
cursor: pointer;
outline:none;
}
a.cssSubmitButton:visited {}
a.cssSubmitButton:hover {
border:1px solid #333;
}
.loading {
background-image:url('load.gif') !important;
color:#ccc !important;
-moz-box-shadow: 0 0 0 #fff !important;
-webkit-box-shadow: 0 0 0 #fff !important;
}
.effect {
border-radius: 5px;
-moz-border-radius: 5px;
-webkit-border-radius: 5px;
}
#success{
text-align:center;
font-size:12px;
margin-top:10px;
display:none;
color:#458B00;
}
#subscribeForm div span.error{
color: #e46c6e;
}
#subscribeForm input.error{
background: #f8dbdb;
border-color: #e77776;
}
#subscribeForm span.error{
color: #e46c6e;
}
</style>
Html Form.
<form method="post" action="" id="subscribeForm" name="subscribeForm">
<fieldset>
<label>Name: </label><input type="text" class="effect" name="name" id="name" >
<span id="nameInfo">What's your name?</span>
</fieldset>
<fieldset>
<label>Email: </label><input type="text" class="effect" name="email" id="email" >
<span id="emailInfo">Valid E-mail please, you will need it to log in!</span>
</fieldset>
<div id="button">
<input type="submit" value="Subscribe" name="subscribeForm"/>
</div>
<div id="success">
<strong>Data Saved Successfully.</strong>
</div>
</form>

Categories