The following is the code for validating a form with radio buttons, text boxes and dropdown list. The javascript for validating radio buttons and textbox works. But the javascript for dropdown doesn't work. Can you tell me what is it that I've done wrong?
Please help!
Thanks in advance.
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
function validateForm()
{
var checked = null;
var name1 = document.forms["information"]["firstname"].value;
var n=name1.split(" ");
var name = n[0];
var sex = document.forms["information"]["sex"];
var e = document.getElementById("prof1");
var strUser = e.options[e.selectedIndex].value;
var strUser1 = e.options[e.selectedIndex].text;
if(name == null || name== "")
{
alert('Enter First Name');
return false;
}
for (var i=0;i<2;i++)
{
if(sex[i].checked)
{
checked = sex[i];
return true;
}
}
if (checked == null)
{
alert(' Enter Sex');
return false;
}
if(strUser==0)
{
alert("Enter Profession");
return false;
}
}
</script>
</head>
<body>
<form name="information" onsubmit="return validateForm()" method="post">
<text style="color:red">*</text> First Name: <input type="text" name="firstname"><br><br>
Last Name: <input type="text" name="lastname"><br><br>
<text style="color:red">*</text> Sex: <input type="radio" name="sex" value="Male"> Male
<input type="radio" name="sex" value="Female"> Female <br><br>
<text style="color:red">*</text> Profession:
<select id="prof1">
<option value="0"> Select </option>
<option value="1"> Engineer </option>
<option value="2"> Doctor </option>
<option value= "3"> Lawyer </option>
<option value="4"> Others </option>
</select>
<input type="submit" value="Submit" />
</form>
</body>
</html>
if(sex[i].checked)
{
checked = sex[i];
return true;
}
Remove return true above.
for ( var i = 0; i < 2; i++) {
if (sex[i].checked) {
checked = sex[i];
//return true;
}
}
Uncomment the return true;
The return statement inside the loop return the value and this results to non-execution of code written after this return statement.
2.
if(strUser==0)
replace with
if(strUser=="0")
Reason :
http://www.w3schools.com/jsref/prop_select_selectedindex.asp
http://www.w3schools.com/jsref/prop_option_value.asp
Related
My find matches function does not seem to be working.
I want to get an array ([]) element by id and do comparisons with it.
The function is supposed to go into the array and generate a random person, then display the match in the text area "showmatches".
I am not sure if the random person is being generated nor if the criteria are being matched in the comparison.
<html>
<head>
<script>
var records = [];
function calculateAge()
{
var dob = document.getElementById('dob').value;
var dobInput = new Date(dob);
var now = new Date();
var year = now.getFullYear();
var month = now.getMonth();
var day = now.getDate();
var birthyear = dobInput.getFullYear();
var birthmonth = dobInput.getMonth();
var birthday = dobInput.getDate();
var bYear = year - birthyear;
var bMonth = month - birthmonth;
var bDay = day - birthday;
if (bYear < 18 || bYear > 75)
{
alert("Age cannot be less than 18 or greater than 75");
return false;
}else{
document.getElementById("age").value = bYear + "years old";
}
//document.getElementById("age").value = bYear + "years old";
}
function showAll()
{
show = document.getElementById("showallpersons").innerHTML=records;
show.value = records.join("\n");
}
(window.onload = () => {
var findmatches=document.getElementById('findmatches');
if(findmatches){
findmatches.addEventListener('click', findMatches, false);
}
function findMatches(e)
{
e.preventDefault();
for(var counter=0; counter<records.length; counter++)
{
var currposn = records[counter].value;
var show = document.getElementById("showallmatches").innerHTML= currposn.fname + currposn.lname;
show.value = currposn.join("\n");
do
{
//From here
var randpson = Math.random() * records.length;
randpson = Math.floor(randpson); //To here works, I know that for sure
//I'm not sure if the conditions for the if statements are correct
if(((randpson.age - currposn.age) <= 10) || ((randpson.age - currposn.age) >= 20))
{
if(((randpson.height - currposn.height) <= 10) || ((randpson.height - currposn.height) >= 20))
{
var display = document.getElementById("showmatches").innerHTML= "Matched to: " +randpson.fname + randpson.lname;
//display.value = "Matched to: " + randpson.fname + randpson.lname;
break;
}
}
} while(counter < 10){
//var newDisplay = document.getElementById("showallmatches").innerHTML= null;
}
//console.log(findMatches());
}
}
})()
(window.onload = () => {
var submit = document.getElementById('submit');
if(submit){
submit.addEventListener('click', addnew, false);
}
function addnew(event)
{
//Prevents default submit event
event.preventDefault();
//Accept values entered in form
var fname = document.getElementById('fname').value;
var mname = document.getElementById('mname').value;
var lname= document.getElementById('lname').value;
var dob= document.getElementById('dob').value;
var gender = document.forms['Information']['gender'].value;
var age = document.getElementById('age').value;
parseInt(age);
var bodyType = document.getElementById('Body Type').value;
var occu= document.getElementById('occu').value;
var height= document.getElementById('height').value;
if (fname==null || fname=="")
{
alert("A first name is required");
return false;
}
if(mname==null || mname=="")
{
alert("A middle initial is required");
return false;
}
if (lname==null || lname=="")
{
alert("A last name is required");
return false;
}
if(dob==null || dob=="")
{
alert("A DOB is required");
return false;
}
if (gender == "")
{
alert("Please select a gender");
return false;
}
if(height <= 170 || height >= 200)
{
alert("A height between 170, not less and 200, not more is required");
return false;
}
if(bodyType==null || bodyType==""){
alert("Please choose a body type");
return false;
}
if(occu==null || occu=="")
{
alert("Please enter an occupation");
return false;
}
//Append To array
records.push(fname);
records.push(mname);
records.push(lname);
records.push(gender);
records.push(age);
records.push(bodyType);
records.push(occu);
records.push(height);
for(i=0;i<records.length;i++)
{
console.log(records[i]);
}
document.getElementById("Information").reset();
}
})()
</script>
</head>
<body>
<div class="wrapper">
<header class="page-header">
<nav>
<button class="cta-contact">Contact Us</button>
</nav>
</header>
</div>
<div class="space">
<h1>
<marquee behavior="scroll" direction="right">What are you waiting for? Find your "one" now.</marquee>
</h1>
</div>
<div class="container">
<form name="Information" id="Information">
<fieldset>
<legend>Personal Information</legend>
First Name:
<input id="fname" type="text" size=40 placeholder='First Name' minlength=4 maxlength=40 required />
<br/><br/>
Middle Initial:
<input id="mname" type="text" size=3 placeholder='M Intial' maxlength=1 required />
<br/><br/>
Last Name:
<input id="lname" type="text" size='40' placeholder='Last Name' minlength='4' maxlength='40' required />
<br/><br/>
Date of Birth
<input id="dob" type="date" onchange="calculateAge()"/>
<br/><br/>
Gender:
<input id="male" type="radio" value='M' name="gender" required/> Male
<input id="female" type="radio" value='F' name="gender" required/> Female
<br/><br/>
Age: <input type="text" id="age" disabled />
<br/>
Body Type:
<select id="Body Type">
<optgroup label="Female" id="FemaleOpt">
<option value="Apple"> Apple </option>
<option value="Pear"> Pear </option>
<option value="Pencil"> Pencil </option>
<option value="Hourglass"> Hourglass </option>
<option value="Round"> Round </option>
</optgroup>
<optgroup label="Male" id="MaleOpt">
<option value="Oval"> Oval </option>
<option value="Triangle"> Triangle </option>
<option value="Rectangle"> Rectangle </option>
<option value="Rhomboid">Rhomboid </option>
<option value="Inverted">Inverted Triangle</option>
</optgroup>
</select>
<br/><br/>
Occupation:
<input id="occu" type="text" size=30 maxlength=30 required />
<br/><br/>
Height(in cm):
<input id="height" type="number" size="3" min="171" max="199" value="" required /><br>
<br/><br/>
<textarea id="showallpersons" name="Show All Persons" onclick="showAll()" disabled></textarea>
<textarea id="showmatches" name="Show All Matches" onclick="findMatches()" disabled></textarea>
<br/><br/>
<button id="submit" type="submit">Submit</button>
<button id="findmatches" type="button">Find Matches</button>
</fieldset>
</form>
</div>
</body>
</html>
Do these steps. First you have two window.onload = () (As you are not using addEventListener only one event will be attached).
Steps:
Keep everything intact, just remove the window.onload from both places. Keep all code inside load intact.
Move the entire code block just to the bottom of the html above closing tag. (Doing so, will make window.onload redundant.)
Put console.log() in the click handler and see if it's working (it will)
Let us know.
NOTE: On other hand there are better way to code this, for e.g wait for DOMContentLoaded for attaching event etc., but it's too big to discuss here. First make this work, then we can recommend better approaches.
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>
How to Enable/Disable input field based on a dropdown selection. and also I should take the user data in JSP based on the selection.
<form action="../jsp/findActorbyChar.jsp">
<h3>Search by:
<select name ="nameField"> </h3>
<option> Only FirstName </option>
<option> Only LastName </option>
<option> Or </option>
<option> And </option>
</select>
<br><br>
First Name <input type="text" name="firstName"/>
Last Name <input type="text" name="lastName"/>
<br><br>
<input type="submit"/>
<input type="reset"/>
Modified Html as shown below:
<h3>Search by:</h3>
<select name ="nameField" id="nameField">
<option>Only FirstName</option>
<option>Only LastName</option>
<option>Or</option>
<option>And</option>
</select>
<br><br>
First Name <input type="text" name="firstName" id="firstNameInput"/>
Last Name <input type="text" name="lastName" id="lastNameInput" />
<br><br>
<input type="submit"/>
<input type="reset"/>
Javascript code:
var nameField = document.getElementById("nameField");
var firstNameInput = document.getElementById("firstNameInput");
var lastNameInput = document.getElementById("lastNameInput");
nameField.addEventListener("change", function(){
//Update this to your logic...
if(nameField.value === "And"){
firstNameInput.disabled = true;
lastNameInput.disabled = true;
}
});
But I think it would be easier if using JQuery to handle DOM update.
Give your menu an id and then you can access the selected index with menu.options.selectedIndex. From there, you can add an on change handler to the menu and use switch cases to set the disabled attribute of the menu.
<h3>Search by:
<select id="menu" name ="nameField"> </h3>
<option> Only FirstName </option>
<option> Only LastName </option>
<option> Or </option>
<option> And </option>
</select>
<br><br>
First Name <input id="first" type="text" name="firstName"/>
Last Name <input id="last" type="text" name="lastName"/>
<br><br>
<input type="submit"/>
<input type="reset"/>
<script type="text/javascript">
var menu = document.getElementById('menu');
var first = document.getElementById('first');
var last = document.getElementById('last');
menu.onchange = function(){
var enableFirst = false, enableLast = false;
switch(menu.options.selectedIndex){
case 0:
enableFirst = true;
enableLast = false;
break;
case 1:
enableFirst = false;
enableLast = true;
break;
case 2:
/*not sure which results you want here*/
break;
case 3:
/*not sure which results you want here*/
break;
default:
break;
}
first.disabled = !enableFirst;
last.disabled = !enableLast;
}
</script>
My code: still all the input fields are enabled
enter code here
<script src="script.js">
var nameField = document.getElementById("nameField");
var firstNameInput = document.getElementById("firstNameInput");
var lastNameInput = document.getElementById("lastNameInput");
nameField.addEventListener("change", function(){
//Update this to your logic...
<script src="script.js">
var nameField = document.getElementById("nameField");
var firstNameInput = document.getElementById("firstNameInput");
var lastNameInput = document.getElementById("lastNameInput");
nameField.addEventListener("change", function(){
//Update this to your logic...
if(nameField.value === "And"){
firstNameInput.disabled = true;
lastNameInput.disabled = true;
}
else if(nameField.value === "firstNameInput"){
firstNameInput.disabled = false;
lastNameInput.disabled = true;
}
else if(nameField.value === "lastNameInput"){
firstNameInput.disabled = true;
lastNameInput.disabled = false;
}
elseif(nameField.value === "lastNameInput"){
firstNameInput.disabled = true;
lastNameInput.disabled = true;
}
});
</script>
Can you please take a look at This Demo and let me know why this bug is happening during the validation of two type of input selections?
Technically, what is happening is if user not select either of checkboxes and Select options and push the submit button the error message shows up and the validRequest boolean stays in false. Now if user ONLY select the checkboxes the situation is same the validRequest boolean is false and error message shows up BUT if user forgets to select the checkboxes and only selects from the list the validateQuery() validates the validRequest as True and then now error message and alert message pops up!
Can you please let me know why this is happening?
$(function () {
var validRequest = false;
function validateQuery() {
var selectedDoll = $('input:checkbox[name=doll]');
if ($(selectedDoll).is(':checked')) {
validRequest = true;
$('#err').html('');
} else {
validRequest = false;
$('#err').html('Some Thing Wrong!');
}
var selectedIcecream = $("#icecream").val();
if (selectedIcecream == 0) {
validRequest = false;
$('#err').html('Some Thing Wrong!');
} else {
validRequest = true;
$('#err').html('');
}
}
$("#isValid").on("click", function () {
validateQuery();
if(validRequest){ alert('Ready To Go');}
console.log(validRequest);
});
});
#err{color:red;}
<div>
<input type="checkbox" name="doll" value="cat" />Cats
<br />
<input type="checkbox" name="doll" value="dog" />Dogs
<br />
<input type="checkbox" name="doll" value="bird" />Birds
<br />
<br />
<select id="icecream">
<option value="0">Select From List</option>
<option value="chocolate">Chocolate</option>
<option value="vanilla">Vanilla</option>
<option value="strawberry">Strawberry</option>
<option value="caramel">Caramel</option>
</select>
</div>
<p>
<input type="submit" id="isValid" value="Submit now" />
</p>
<p>
<div id="err"></div>
</p>
Fixed: http://jsfiddle.net/byk309j8/7/
The problem was that you had 2 independent if statements while you must have only one. Also you were checking if the select box is empty == 0 instead of not empty !== 0
$(function () {
var validRequest = false;
function validateQuery() {
var selectedDoll = $('input:checkbox[name=doll]');
var selectedIcecream = $("#icecream").val();
// checkbox is not checked, but select is
if ($(selectedDoll).is(':checked') && selectedIcecream == 0) {
validRequest = false;
$('#err').html('select not selected');
} else if ($(selectedDoll).is(':checked') == false && selectedIcecream != 0) {
validRequest = false;
$('#err').html('checkbox not checked');
} else if ($(selectedDoll).is(':checked') == false || selectedIcecream == 0) {
validRequest = false;
$('#err').html('checkbox not checked or select not selected');
} else {
validRequest = true;
$('#err').html('');
}
}
$("#isValid").on("click", function () {
validateQuery();
if(validRequest){ alert('Ready To Go');}
console.log(validRequest);
});
});
<div>
<input type="checkbox" name="doll" value="cat" />Cats
<br />
<input type="checkbox" name="doll" value="dog" />Dogs
<br />
<input type="checkbox" name="doll" value="bird" />Birds
<br />
<br />
<select id="icecream">
<option value="0">Select From List</option>
<option value="chocolate">Chocolate</option>
<option value="vanilla">Vanilla</option>
<option value="strawberry">Strawberry</option>
<option value="caramel">Caramel</option>
</select>
</div>
<p>
<input type="submit" id="isValid" value="Submit now" />
</p>
<p>
<div id="err"></div>
</p>
#err{color:red;}
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 :)