registration form validation using javascript - javascript

Im partly there but it would be helpful if any of you guys could send the entire code .
1) Create a form with the below given fields and validate the same using javascript or jquery.
Name : Text box- mandatory
Gender : Radio Button
Age : Text box - Accept Number only - (check for valid Age criteria)
Email : Text box -  should be in format example#gmail.com
Website : Text box -  should be in format http://www.example.com
Country : Select box with 10 countries
Mobile :  Text box - should be a 10 digit number - Display this field only after the user selects a country
Social Media Accounts : Facebook, Google, Twitter (3 checkboxes) - Display Social media section only if selected Country is India
I agree the Terms and Conditions - Checkbox
All fields are mandatory and show error messages for all fields(if not valid)
Only allow to submit form after checking the 'I agree' checkbox.

<!DOCTYPE html>
<html>
<head>
<title>Get Values Of Form Elements Using jQuery</title>
<!-- Include CSS File Here -->
<link rel="stylesheet" href="form_value.css"/>
<!-- Include JS File Here -->
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script type="text/javascript" src="form_value.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$("#social").hide() ;
// $("#hide").click(function(){
// $("social").hide();
// });
// var country = document.getElementByName("country")[0].value;
// if (country.value == "India") {
// $("#show").click(function(){
//     $("social").show();
// });
// }
if (!(/^\w+([\.-]?\w+)*#\w+([\.-]?\w+)*(\.\w{2,3})+$/).test(document.email_id.value)) {
alert("You have entered an invalid email address!")
return (false)
}
});
</script>
</head>
<body onload="disableSubmit()">
<div class="container">
<div class="main">
<h2>Get Values Of Form Elements Using jQuery</h2>
<form action="">
<!-- Text -->
<br>
<br>
<label>Name :</label>
<input type="text" id="text" name="name" value=""required/><br>
<!-- Radio Button -->
<br><br><br>
<label>Gender:</label>
<input type="radio" name="male" value="Male">Male
<input type="radio" name="female" value="Female">Female
<br><br>
<!-- Textarea -->
<label>Email :</label>
<input type="text" id="Email" value="" id="Email"/>
<br>
<br><br>
Age: <input type="text" id="Age" onkeypress="return IsNumeric(event);" ondrop="return false;" onpaste="return false;" />
<span id="error" style="color: Red; display: none">* Input digits (0 - 9)</span>
<br><br>
<label> Website:</label>
<input type="text" id="text" value="" name = "Website" id="website" />
<script type="text/javascript">
function validate() {
if(Website.value.length==0)
{
document.getElementById("Website").innerHTML="Should be in the format http://www.example.com ";
}
}
</script>
<br><br>
<label>Country:</label>
<select class="country" id = "country">
<option>Select</option>
<option value="usa">United States</option>
<option value="india">India</option>
<option value="uk">United Kingdom</option>
<option value="uae">United Arab Emirates</option>
<option value="germany">Germany</option>
<option value="france">France</option>
<option value="netherlands">Netherlands</option>
<option value="yemen">Yemen</option>
<option value="pakistan">Pakistan</option>
<option value="russia">Russia</option>
</select>
<br><br>
<label>Mobile:</label>
<input type="text" id="phone" name="phone" onkeypress="phoneno()" maxlength="10">
<script type="text/javascript">
function phoneno(){
$('#phone').keypress(function(e) {
var a = [];
var k = e.which;
for (i = 48; i < 58; i++)
a.push(i);
if (!(a.indexOf(k)>=0))
e.preventDefault();
});
}
</script>
<br><br>
<div id = "social" >
<p>Social Media Accounts.</p> <input type="checkbox" id="Facebook" value="Facebook"><label for="Facebook"> Facebook</label><br> <input type="checkbox" id="Google" value="Google"><label for="Google"> CSS</label><br> <input type="checkbox" id="Twitter" value="Twitter"><label for="Twitter"> Twitter</label><br>
</div>
<br>
<br>
<script>
function disableSubmit() {
document.getElementById("submit").disabled = true;
}
function activateButton(element) {
if(element.checked) {
document.getElementById("submit").disabled = false;
}
else {
document.getElementById("submit").disabled = true;
}
}
</script>
<input type="checkbox" name="terms" id="terms" onchange="activateButton(this)"> I Agree Terms & Coditions
<br><br>
<input type="submit" name="submit" id="submit">
</script>
</form>
</div>
</body>
</html>

this is my js page content form_value.js
$(document).ready(function() {
// Function to get input value.
$('#text_value').click(function() {
var text_value = $("#text").val();
if(text_value=='') {
alert("Enter Some Text In Input Field");
}else{
alert(text_value);
}
});
// Funtion to get checked radio's value.
$('#gender_value').click(function() {
$('#result').empty();
var value = $("form input[type='gender']:checked").val();
if($("form input[type='gender']").is(':checked')) {
$('#result').append("Checked Radio Button Value is :<span> "+ value +" </span>");
}else{
alert(" Please Select any Option ");
}
});
// Get value Onchange radio function.
$('input:gender').change(function(){
var value = $("form input[type='gender']:checked").val();
alert("Value of Changed Radio is : " +value);
});
// Funtion to reset or clear selection.
$('#radio_reset').click(function() {
$('#result').empty();
$("input:radio").attr("checked", false);
});
$('#Email').click(function() {
function validate(Email) {
var reg = /^([A-Za-z0-9_\-\.])+\#([A-Za-z0-9_\-\.])+\.([A-Za- z]{2,4})$/;
//var address = document.getElementById[email].value;
if (reg.test(email) == false)
{
alert('Should be in the format example#gmail.com');
return (false);
}
}
});
});
$("#Age").click(function() {
var specialKeys = new Array();
specialKeys.push(8); //Backspace
function IsNumeric(e) {
var keyCode = e.which ? e.which : e.keyCode
var ret = ((keyCode >= 48 && keyCode <= 57) || specialKeys.indexOf(keyCode) != -1);
document.getElementById("error").style.display = ret ? "none" : "inline";
return ret;
}
function handleChange(input) {
if (input.value < 0) input.value = 0;
if (input.value > 100) input.value = 100;
}
});
</script>

<!DOCTYPE html> <html> <head> <script> function validateForm() {
var name = document.forms["myForm"]["fname"].value;
var gender = document.forms["myForm"]["gender"].value;
var age = document.forms["myForm"]["age"].value;
var a = parseInt(age);
var email = document.forms["myForm"]["email"].value;
var url = document.forms["myForm"]["website"].value;
var country = document.forms["myForm"]["country"].value;
var mobileCountry = document.forms["myForm"]["mobileCountry"].value;
var mcLength = mobileCountry.length;
if (name == "") {
alert("Name Field is mandatory");
return false;
}
if (gender != "male" && gender != "female") {
alert("Atleast one Gender has to be chosen");
return false;
}
if(isNaN(a)){
alert("Age is compulsory and must be a number");
return false;
}
if(email == ""){
alert("Email address is required");
}
else if(/^\w+([\.-]?\w+)*#\w+([\.-]?\w+)*(\.\w{2,3})+$/.test(email)){
} else{
alert("Email address entered is invalid");
return false;
}
if(/^(ftp|http|https):\/\/[^ "]+$/.test(url)){
} else{
alert("Website url entered is invalid");
return false;
}
if(country != "choose"){
document.getElementById("mc").style.display = "block";
} else{
document.getElementById("mc").style.display = "none";
}
if(mcLength != 10){
alert("Number must be ten digits");
return false;
}
} function displaySocial(){ var social =
document.getElementById("social");
var mc = document.getElementById("mobileCountry");
var country = document.getElementById("country");
var selectedValue = country.options[country.selectedIndex].value;
if (selectedValue != "choose") {
if(selectedValue == "india"){
if(social.style.display = "none"){
social.style.display = "block";
} else{
social.style.display = "none";
} } else{
social.style.display = "none"; }
if(mc.style.display = "none"){
mc.style.display = "block";
} else{
mc.style.display = "none"; } } else{
mc.style.display = "none"; }
} </script> </head> <body> <form name="myForm" action="/action_page_post.php" onsubmit="return validateForm()" method="post"> Name: <input type="text" name="fname"><br> Gender: <input type="radio" name="gender" value="male"> Male <input type="radio" value="female" name="gender"> Female <br> age: <input type="text" name="age"><br> email: <input type="text" name="email"><br> website: <input type="text" name="website"><br> country: <select type="text" name="country" id="country" onclick="displaySocial()"><option value="choose">--choose--</option><option value="usa">USA</option><option value="uk">UK</option><option value="ng">Nigeria</option><option value="india">India</option></select><br> <span id="mobileCountry" style="display: none;">mobile country: <input type="text" name="mobileCountry"><br></span> <span id="social" style="display: none;">Social Media: <input type="radio" name="gender"> Facebook <input type="radio" name="gender"> Google <input type="radio" name="gender"> Twitter</span> <br> <p> <input type="submit" value="Submit"> </form> <p id="error"></p> </body> </html>

Related

Submit Button Not working but if I remove its JavaScript it works

This is my index.html file. It has JavaScript but when JavaScript validation works >Submit button doesn't perform any action. But when I remove JavaScript code it submits the data to the database.
I need to understand where my code has faults or mistakes and why this is happening. How to validate that the arrival date should be smaller than the departure date.
<!DOCTYPE html>
<head>
<title>Book Accomodations</title>
<link rel="stylesheet" href="style.css">
<script>
function validate(){
var x =document.forms["myform"]["fname"].value;
var y =document.forms["myform"]["lname"].value;
var email =document.forms["myform"]["email"].value;
var filter = /^\w+([\.-]?\w+)*#\w+([\.-]?\w+)*(\.\w{2,3})+$/;
var getSelectedValue = document.querySelector( 'input[name="payment"]:checked');
if (x == "" || x == null) {
alert("First Name must be filled out");
return false;
} else if (y == "" || y == null) {
alert(" Last Name must be filled out");
return false;
}
else if (!email.match(filter)) {
alert(" Enter Proper Email ID");
return false;
}
else if(document.getElementById("country").value == "")
{
alert("Please select a country");
return false;
} else if(getSelectedValue == null) {
alert("Select Payment Mode")
return false;
}
return false;
}
</script>
</head>
<body>
<div class="form">
<form name ="myform" action="function.php" onsubmit="return validate();" id="form" method="POST" >
<label for="fname">First Name:</label>
<input type="text" id="fname" name="fname" /><br>
<label for="lname">Last Name:</label>
<input type="text" id="lname" name="lname" /><br>
<label for="email">Email:</label>
<input type="email" id="email" name="email" /><br>
<label for="arrival">Arrival Date:</label>
<input type="date" id="arrival " name="adate" ><br>
<label for="departure">Departure Date:</label>
<input type="date" id="departure " name="ddate" />
<br>
<label for="country">Choose a Country:</label>
<select id="country" name="country" form="myform" >
<option disabled selected value> -- select an option -- </option>
<option value="India">India</option>
<option value="U.S.A.">U.S.A.</option>
<option value="Nepal">Nepal</option>
<option value="Bangladesh">Bangladesh</option>
<option value="Germany">Germany</option>
<option value="Spain">Spain</option>
<option value="Italy">Italy</option>
<option value="Sri Lanka">Sri Lanka</option>
<option value="China">China</option>
</select>
<p>Payment Mode:</p>
<input type="radio" id="deb"
name="payment" value="Debit" />
<label for="deb">Debit Card</label>
<input type="radio" id="cred"
name="payment" value="Credit"/>
<label for="Credit">Credit Card</label>
<br>
<input type="submit" id="submit" name="submit" value="submit" style="width: 100px;"/>
<input type="reset" value="Reset" style="width: 100px; "/>
</form> </div>
</body>
You should return true at the end of your validate() function if your validation was successful. Right now you always return false. Thats why the button doesn´t seams to work.
Seems like you missed something.
You should return true after succesfull validation.
if (x == "" || x == null) {
alert("First Name must be filled out");
return false;
} else if (y == "" || y == null) {
alert("Last Name must be filled out");
return false;
} else if (!email.match(filter)) {
alert("Enter Proper Email ID");
return false;
} else if (document.getElementById("country").value == "") {
alert("Please select a country");
return false;
} else if (getSelectedValue == null) {
alert("Select Payment Mode")
return false;
} else {
return true;
}
Or just return true after if-else statement.

Producing an output box from a form

<!DOCTYPE html>
<html><head><title>CT Traders</title>
<style>
fieldset {width:40%; margin:0px 0px 10px 1%;}
legend {padding:2px; text-indent:5px;}
h2, p {margin-left: 1%;}
input[type="submit"], input[type="reset"]
{display:inline; float:none;}
</style>
<script>
//suggested logic for the validateInput() function
function validateInputs()
{
//check payment method
var methodChecked = false;
for (var i=0; i <document.frmCustOrders.class.length;i++)
{
if (document.frmCustOrders.class[i].checked ==true)
{
classChecked = true;
vClass = document.frmCustOrders.class[i].value;
}
}
//check customer index value
var customerIndex = document.getElementById("customer").value;
//retrieve order quantity
var qty = document.getElementById("qty").value;
//validate form data
if (customerIndex == -1) //validate customer
{
alert("Please select a customer.")
return false;
}
else if () //validate qty
{
}
else if (fsClassChecked == false) //validate payment method
{
alert("Please select a payment method.")
return false;
}
else //output
{
orderEntries = customer+ "\n"+ qty+ "\n"+vClass;
alert(orderEntries);
return false;
}
}
</script>
</head>
<body>
<h2>Customer Order</h2>
<form name="frmCustOrders" id="frmCustOrders"
onsubmit="return validateInputs();" action="">
<fieldset id="fsCustomer">
<legend>Customer List</legend>
<select name="customer" id="customer" size="3">
<option>107 Paula Harris</option>
<option>232 Mitch Edwards</option>
<option>229 BTC</option>
</select>
</fieldset>
<p>
<label for="qty">Order Quantity: </label>
<input type="text" name="qty" id="qty" />
</p>
<fieldset id="fsClass">
<legend>Payment Method</legend>
<input type="radio" name="method" id="check" value="check" />
Check<br />
<input type="radio" name="method" id="creditCard" value="credit card" />
Credit Card<br />
<input type="radio" name="method" id="debitCard" value="debit card" />
Debit Card
</fieldset>
<p> <input type="submit" value="Submit" />
<input type="reset" value="Reset" /></p>
</form>
</body>
</html>
I'm having issues getting an output box that retrieves the selections on the form.
Also, in one of my if statements I'm assigned to check if the value is between 1 and 999 but I'm drawing a total blank on this. I'm new to coding (Javascript) and this is my first class. Any help with getting this to work would be greatly appreciated.
There are some issues with your code
Redundant else if ()
fsClassChecked variable not declared.
Redundant class when iterate elements document.frmCustOrders.class
Use wrong variable customer should be customerIndex
Wrong condition (customerIndex == -1) change to (customerIndex == "")
//suggested logic for the validateInput() function
function validateInputs()
{
//check payment method
var methodChecked = false;
var fsClassChecked = false;
for (var i=0; i <document.frmCustOrders.length;i++)
{
if (document.frmCustOrders[i].checked ==true)
{
fsClassChecked = true;
vClass = document.frmCustOrders[i].value;
}
}
//check customer index value
var customerIndex = document.getElementById("customer").value;
//retrieve order quantity
var qty = document.getElementById("qty").value;
//validate form data
if (customerIndex == "") //validate customer
{
alert("Please select a customer.")
return false;
}
else if(qty == "" || qty < 1 || qty > 999){
alert("Please enter qty 1-999.")
return false;
}
else if (fsClassChecked == false) //validate payment method
{
alert("Please select a payment method.")
return false;
}
else //output
{
orderEntries = customerIndex + "\n"+ qty+ "\n"+vClass;
alert(orderEntries);
return false;
}
return false;
}
<!DOCTYPE html>
<html><head><title>CT Traders</title>
<style>
fieldset {width:40%; margin:0px 0px 10px 1%;}
legend {padding:2px; text-indent:5px;}
h2, p {margin-left: 1%;}
input[type="submit"], input[type="reset"]
{display:inline; float:none;}
</style>
<script>
</script>
</head>
<body>
<h2>Customer Order</h2>
<form name="frmCustOrders" id="frmCustOrders"
onsubmit="return validateInputs();" action="#">
<fieldset id="fsCustomer">
<legend>Customer List</legend>
<select name="customer" id="customer" size="3">
<option>107 Paula Harris</option>
<option>232 Mitch Edwards</option>
<option>229 BTC</option>
</select>
</fieldset>
<p>
<label for="qty">Order Quantity: </label>
<input type="text" name="qty" id="qty" />
</p>
<fieldset id="fsClass">
<legend>Payment Method</legend>
<input type="radio" name="method" id="check" value="check" />
Check<br />
<input type="radio" name="method" id="creditCard" value="credit card" />
Credit Card<br />
<input type="radio" name="method" id="debitCard" value="debit card" />
Debit Card
</fieldset>
<p> <input type="submit" value="Submit" />
<input type="reset" value="Reset" /></p>
</form>
</body>
</html>

Action attribute not working on JS validated form

The files are in the the correct locations, both the form page and form complete page are in the same folder. When I click submit, it validates the form correctly, but if everything is entered correctly and validates, it does nothing, just takes away the asterisks like it's supposed to in the js. I want it to link to the form_complete.html page after you hit submit and the validation runs, but after it validates nothing happens,
The html:
<form id="contactform" action="form_complete.html" method="post">
<p class = "labelp">
<label for="name">Name: </label>
<input type="text" name="name" id="name" placeholder="Enter your name" >
<span>*</span><br><br>
</p>
<p class = "labelp">
<label for="age">Age: </label>
<input type="text" min="18" max="100" name="age" id="age" placeholder="Enter your age">
<!-- using type=text so I can practice isNaN in js -->
<span>*</span><br><br>
</p>
<p class = "labelp"></p>
<label for="country">Country: </label>
<select name="country" id="country">
<option value ="">Select a country</option>
<option>USA</option>
<option>Canada</option>
<option>Mexico</option>
<option>Brazil</option>
<option>Japan</option>
<option>China</option>
<option>Other</option>
</select>
<span>*</span><br><br>
</p>
<p class = "labelp">
<label for="email">E-mail: </label>
<input type="email" name="email" id="email" placeholder="Enter your E-mail">
<span>*</span><br><br>
</p>
<p class = "labelp">
<label for="bday">Birthday: </label>
<input type="date" name="bday" id="bday">
<span>*</span><br><br>
</p>
<p class = "labelp">
<label for="gender" id="gender">Gender: </label>
<input type="radio" name="gender" value="male" id="male"> Male
<input type="radio" name="gender" value="female" id="female"> Female
<input type="radio" name="gender" value="other" id="other"> Other
<br><br>
</p>
<label>Comments: </label>
<textarea rows="5" cols="30"> </textarea><br><br>
<input type="button" id="registerbtn" value="Submit">
<input type="button" id="resetbtn" value="Reset">
</form>
The javascript:
"use strict";
var $ = function(id) { return document.getElementById(id);};
var processEntries = function(){
var isValid = true;
// values
var name = $("name").value;
var age = $("age").value;
var country = $("country").value;
var email = $("email").value;
var bday = $("bday").value;
var gender = "";
if ($("male").checked){gender = "Male";}
if ($("female").checked){gender = "Female";}
if ($("other").checked){gender = "Other";}
console.log(gender); //check if gender buttons work
// name
if(name == ""){
$("name").nextElementSibling.firstChild.nodeValue = "This field is required!";
isValid = false;}
else{
$("name").nextElementSibling.firstChild.nodeValue = "";
}
// age
if(age == ""){
$("age").nextElementSibling.firstChild.nodeValue = "This field is required!";
isValid = false;
}
else if(isNaN(age)){
$("age").nextElementSibling.firstChild.nodeValue = "This field must be a number!";
isValid = false;
}
else{
$("age").nextElementSibling.firstChild.nodeValue = "";
}
//country
if(country == ""){
$("country").nextElementSibling.firstChild.nodeValue = "Please select a country!";
isValid = false;}
else{
$("country").nextElementSibling.firstChild.nodeValue = "";
}
//email
if(email == ""){
$("email").nextElementSibling.firstChild.nodeValue = "This field is required!";
isValid = false;}
else{
$("email").nextElementSibling.firstChild.nodeValue = "";
}
//birthday
if(bday == ""){
$("bday").nextElementSibling.firstChild.nodeValue = "This field is required!";
isValid = false;}
else{
$("bday").nextElementSibling.firstChild.nodeValue = "";
}
}
var resetForm = function(){
$("contactform").reset();
$("name").nextElementSibling.firstChild.nodeValue = "*";
$("age").nextElementSibling.firstChild.nodeValue = "*";
$("country").nextElementSibling.firstChild.nodeValue = "*";
$("email").nextElementSibling.firstChild.nodeValue = "*";
$("bday").nextElementSibling.firstChild.nodeValue = "*";
}
window.onload = function() {
$("registerbtn").onclick = processEntries;
$("resetbtn").onclick = resetForm;
$("name").focus();
}
Please put below condition at the end of "processEntries" function
if(isValid){
$("#contactform").submit();
}

Adding Span with Class to a input tag with Jquery

I am trying to add a Span after my Input that will have the class "error" and the text "test".
I've tried the append, and insertAfter methods. I can get the code to work on jsfiddle but I cannot get the code to work on my application.
I have put the HTML and JS/Jquery below. My end result would have a Span (with the class error) next to each input with the type text. I would then set a value for this span based on a validation loop.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Zito - Lab 7</title>
<link rel="stylesheet" href="main.css">
<script src="http://html5shiv.googlecode.com/svn/trunk/html5.js" type="text/javascript"></script>
<script src="http://code.jquery.com/jquery-1.8.3.min.js" type="text/javascript"></script>
<script src="reservation.js" type="text/javascript"></script>
</head>
<body>
<h1>Reservation Request</h1>
<form action="response.html" method="get"
name="reservation_form" id="reservation_form">
<fieldset>
<legend>General Information</legend>
<label for="arrival_date">Arrival date:</label>
<input type="text" name="arrival_date" id="arrival_date" autofocus><br>
<label for="nights">Nights:</label>
<input type="text" name="nights" id="nights"><br>
<label>Adults:</label>
<select name="adults" id="adults">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
</select><br>
<label>Children:</label>
<select name="children" id="children">
<option value="0">0</option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
</select><br>
</fieldset>
<fieldset>
<legend>Preferences</legend>
<label>Room type:</label>
<input type="radio" name="room" id="standard" class="left" checked>Standard
<input type="radio" name="room" id="business" class="left">Business
<input type="radio" name="room" id="suite" class="left last">Suite<br>
<label>Bed type:</label>
<input type="radio" name="bed" id="king" class="left" checked>King
<input type="radio" name="bed" id="double" class="left last">Double Double<br>
<input type="checkbox" name="smoking" id="smoking">Smoking<br>
</fieldset>
<fieldset>
<legend>Contact Information</legend>
<label for="name">Name:</label>
<input type="text" name="name" id="name"><br>
<label for="email">Email:</label>
<input type="text" name="email" id="email"><br>
<label for="phone">Phone:</label>
<input type="text" name="phone" id="phone" placeholder="999-999-9999"><br>
</fieldset>
<input type="submit" id="submit" value="Submit Request"><br>
</form>
</body>
</html>
JS/JQuery
$(document).ready(function() {
var emailPattern = /\b[A-Za-z0-9._%+-]+#[A-Za-z0-9.-]+\.[A-Za-z]{2,4}\b/;
var phonePattern = /\b(\d{3})([-])(\d{3})([-])(\d{4})\b/;
var datePattern = /\b(0[1-9]|1[012])([/])(0[1-9]|1[0-9]|2[0-9]|3[01])([/])((20)\d\d)\b/;
$(":text").after("<span class='error'>*</span>");
$("#arrival_date").focus();
$("#reservation_form").submit(
function(event) {
var isValid = true;
// validate arrival date
var arrivalDate = $("#arrival_date").val();
if (arrivalDate == "") {
$("#arrival_date").next().text("This field is required");
isValid = false;
} else if (!datePattern.test(arrivalDate)) {
$("#arrival_date").next().text("Must be in the format 12/12/2012");
isValid = false;
} else {
$("#arrival_date").next().text("");
}
// validate nights
var nights = $("#nights").val();
if (nights == "") {
$("#nights").next().text("This field is required");
isValid = false;
} else if ((isNaN(parseInt(nights))) || (parseInt(nights) <=0)) {
$("#nights").next().text("This field must be a number and not zero");
isValid = false;
} else {
$("#nights").next().text("");
}
// validate name
var name = $("#name").val();
if (name == "") {
$("#name").next().text("This field is required");
isValid = false;
} else {
$("#name").next().text("");
}
// validate email
var email = $("#email").val();
if (email == "") {
$("#email").next().text("This field is required");
isValid = false;
} else if (!emailPattern.test(email) ) {
$("#email").next().text("Must be a valid email address.");
isValid = false;
} else {
$("#email").next().text("");
}
// validate phone
var phone = $("#phone").val();
if (phone == "") {
$("#phone").next().text("This field is required");
isValid = false;
} else if (!phonePattern.test(phone) ) {
$("#phone").next().text("Must be in the format 999-999-9999");
isValid = false;
} else {
$("#phone").next().text("");
}
if (isValid == false) {
event.preventDefault();
$("#arrival_date").focus();
}
}
);
}); // end ready
Most easy way is to add a Div container around the form and just append the warning to that. To effectively append after an element you need to give it a class or id.
var email = $("#email"); //using class instead of input:text
var html = "<span class='error'>TEST!</span>"
email.after( html );
But I personally would like something like this better:
var generateError = function(){
var html = "<div id='error' style='top: 0; left:0; width:100%; height: 50px; background-color: red; text-allign: center; display:none; z-index: 100;'> ERROR!!</div>"
$(body).append( html );
}
var showError = function( text ){
var err = $("#error");
err.html( text );
err.show(500).delay(2000).hide(500);
}
Code is fairly self-explaining, but this will make two functions: generateError and showError.
generateError you need to call before you want to show the error, possibly when the page loads it will add a small header on top of all you other elements and will appear hidden.
showError uses a text argument with the error you want to show. Then it will set the text to the div and show it for two seconds.
This then is more what you are looking for?
$(document).ready(function () {
var input = $("input");
var emailPattern = /\b[A-Za-z0-9._%+-]+#[A-Za-z0-9.-]+\.[A-Za-z]{2,4}\b/;
input.keypress(function (ele) {
// if regex.test( input ) === false
createErrors(ele.target);
})
});
var createErrors = function (ele) {
$('<span>TEST!</span>').insertAfter(ele);
$("#arrival_date").focus();
};
This works on keypress, that means the regex gets checked every time a key is pressed. It also passes the element where the user is typing as parameter, this means that you wont get errors for all input:text, but only for the ones where there is an error.
Updated Fiddle (still not perfect, but if its an school exercise this will help you to finish it :)

Making JS Alert Look More Professional

Can someone help me make this alert look much nicer? Like Maybe split up Each text box on its own line? I can not figure out how to make this look a lot cleaner and not just all piled on one line.
To see alert hit Lien radio button and then hit next without filling textboxes
http://jsfiddle.net/t4Lgm0n2/9/
function validateForm(){
var QnoText = ['lien']; // add IDs here for questions with optional text input
var ids = '';
flag = true;
for (i=0; i<QnoText.length; i++) {
CkStatus = document.getElementById(QnoText[i]).checked;
ids = QnoText[i]+'lname';
var eD = "";
if (CkStatus && document.getElementById(ids).value == '') {
eD = eD+' lienholder name';
document.getElementById(ids).focus();
flag = false;
}
ids2 = QnoText[i]+'laddress';
if (CkStatus && document.getElementById(ids2).value == '') {
eD=eD+' lienholder address';
document.getElementById(ids2).focus();
flag = false;
}
ids3 = 'datepicker2';
if (CkStatus && document.getElementById(ids3).value == '') {
eD=eD+' lien date';
document.getElementById(ids3).focus();
flag = false;
}
if(eD!="") alert("Please enter "+eD);
}
return flag;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<input type="radio" value="Yes" name="lien" id="lien" required="yes" onchange="showhideForm(this.value);"/><label for="lien">Lien</label>
<input type="radio" value="None" name="lien" id="nolien" onchange="showhideForm(this.value);"/><label for="nolien">No Lien</label>
<script type="text/javascript">
function showhideForm(lien) {
if (lien == "Yes") {
document.getElementById("div1").style.display = 'block';
document.getElementById("div2").style.display = 'none';
}
else if (lien == "None") {
document.getElementById("div2").style.display = 'block';
document.getElementById("div1").style.display = 'none';
$("#div1 > .clearfix input:text").val("");
}
}
</script>
<div id="div1" style="display:none">
<div class="clearfix">
<label for="lname">Lienholder Name:</label>
<input type="text" name="lienlname" validateat="onSubmit" validate="maxlength" id="lienlname" size="54" maxlength="120" message="Please enter lienholder name." value="">
</p>
<p>
<label for="laddress">Lienholder Address:</label>
<input type="text" name="lienladdress" validateat="onSubmit" validate="maxlength" id="lienladdress" size="54" maxlength="120" message="Please enter lienholder address." value="">
</p>
<p>
<label for="ldate">Date of Lien:</label>
<input type="text" name="lienldate" id="datepicker2" mask="99/99/9999" value="">
</div>
</div>
<div id="div2" style="display:none">
<!---You are not qualified to see this form.--->
</div>
<input type="submit" name="submit" value="Next" onclick="validateForm()">
You can use new line characters \n to make text more readable:
var eD = [];
if (CkStatus && document.getElementById(ids).value == '') {
eD.push('Please enter lienholder name');
document.getElementById(ids).focus();
flag = false;
}
// ...
if (eD.length) alert(eD.join('\n'));
As you can see I'm also pushing error messages into ed array, which makes it more convenient to concatenate resulting message using .join() method.
Demo: http://jsfiddle.net/t4Lgm0n2/11/

Categories