Validating a Form with text boxes and radio buttons using JavaScript - javascript

I am trying to make an order form that validates all entries to make sure the text boxes have data, and that the one of the 3 radio buttons is selected. As you can see in my code, I used a function to validate all the text boxes that are required, but I can not get the radio buttons to validate. I have tried if else statements and loops, but none of them have worked for me. I have tried including the radio button validation in the current function, and also tried making a new function just for it. Please help!
HTML here:
<form action="FormProcessor.html.html" method="get" onsubmit="return check();">
<select>
<option>Hand Tool</option>
<option>Saw</option>
<option>Hammer</option>
<option>Screwdriver</option>
<option>Wrench</option>
<option>Pliers</option>
</select>
<select>
<option>Power Tools</option>
<option>Circular Saw</option>
<option>Sabre Saw</option>
<option>Drill</option>
<option>Belt Sander</option>
<option>Table Saw</option>
</select>
<label>
<select>
<option>Materials</option>
<option>Plywood</option>
<option>Shingles</option>
<option>Nails</option>
<option>Screws</option>
</select>
</label>
<label>First Name
<input type="text" id="firstname" name="firstname" placeholder="First Name"></label>
<label>Last Name
<input type="text" id="lastname" name="lastname" placeholder="Last Name"></label> <br><br>
<label>Street Address 1
<input type="text" id="street_address_1" name="street_address_1" placeholder="Address 1"></label> <br><br>
<label>Street Address 2
<input type="text" id="street_address_2" name="street_address_2" placeholder="Address 2"></label> <br><br>
<label>City
<input type="text" id="city" name="city" placeholder="City"></label>
<label>State
<input type="text" id="state" name="State" placeholder="State"></label>
<label>Zip
<input type="text" id="zip_code" name="zip_code" placeholder="Zip"></label> <br><br>
<label>Phone
<input type="text" id="phone" name="phone" placeholder="Phone"></label>
<label>Fax
<input type="text" id="fax" name="fax" placeholder="Fax"></label> <br><br>
<label>Payment Method?
<input type="radio" name="card_type" id="visa">
<label for="visa">Visa</label>
<input type="radio" name="card_type" id="mastercard">
<label for="mastercard">MasterCard</label>
<input type="radio" name="card_type" id="americanexpress">
<label for="americanexpress">American Express</label><br><br>
<label>Credit Card Number
<input type="text" id="credit_card_number" name="credit_card_number" placeholder="Credit Card Number"></label> <br><br>
<label>Experiation Month
<select id = month>
<option>Month</option>
<option>01</option>
<option>02</option>
<option>03</option>
<option>04</option>
<option>05</option>
<option>06</option>
<option>07</option>
<option>08</option>
<option>09</option>
<option>10</option>
<option>11</option>
<option>12</option>
</select>
</label>
<label>Experiation Year
<select id = year>
<option>Year</option>
<option>2010</option>
<option>2011</option>
<option>2012</option>
<option>2013</option>
<option>2014</option>
<option>2015</option>
</select> <br>
</label> <br><br>
<input type="submit" value="Submit Order">
JS Here
function check() {
var errormessage = "";
if (document.getElementById('firstname').value == "") {
errormessage += 'Please enter a First Name \n';
}
if (document.getElementById('lastname').value == "") {
errormessage += 'Please enter a Last Name \n';
}
if (document.getElementById('street_address_1').value == "") {
errormessage += 'Please enter your Street Address \n';
}
if (document.getElementById('city').value == "") {
errormessage += 'Please enter a City \n';
}
if (document.getElementById('state').value == "") {
errormessage += 'Please enter a State \n';
}
if (document.getElementById('zip_code').value == "") {
errormessage += 'Please enter a Zip Code \n';
}
if (document.getElementById('phone').value == "") {
errormessage +='Please enter a Phone Number \n';
}
if (document.getElementById('credit_card_number').value == "") {
errormessage += 'Please enter a Credit Card \n';
}
if (document.getElementById('month').value == "") {
errormessage += 'Please enter a Month \n';
}
if (document.getElementById('year').value == "") {
errormessage += 'Please enter a Year \n';
}
if (errormessage != "") {
alert(errormessage);
return false;
}
}

How about setting up a function to validate a radio button, something like this:
function validateRadio(radioGroup) {
for (i = 0; i < radioGroup.length; ++ i) {
if (radioGroup[i].checked) return true;
}
return false;
}
And then in your check() function you can call the validateRadio() function and pass it the radio group you want to check:
if(!validateRadio(document.forms["formid"]["card_type"])) {
errormessage +='Please select a Payment Method\n';
}

Related

Form Validation Issues Javascript

I'm trying to get my HTML & Javascript code to generate a similar prompt (see image below something similar in principle). Instead of the prompt working a page called "HTML - Form Data Extraction Test" comes up instead.
Struggling to pin point where I'd gone wrong as my labels and ID's are in place, I've been using "getelementbyid", defined all the instances of when the messages should appear.
Any help would be greatly appreciated. Thanks in advance.
/* function validate()will validate form data */
function validate() {
var jref = document.getElementById("jref").value;
var fname = document.getElementById("fname").value;
var lname = document.getElementById("lname").value;
var dob = document.getElementById("dob").value;
var email = document.getElementById("email").value;
var genm = document.getElementById("genm").checked;
var genf = document.getElementById("genf").checked;
var saddress = document.getElementById("saddress").value;
var stown = document.getElementById("stown").value;
var pnumber = document.getElementById("pnumber").value;
//NEED LABELS FOR
//state dropdown
//Skills drop down
var errMsg = "";
var result = true; /* assumes no errors */
//var pattern = /^[a-zA-Z ]+$/; /* regular expression for letters and spaces only */
if (jref == "") {
errMsg += "Job Reference Number cannot be Empty\n";
//errMsg = errMsg + "First Name cannot be
}
if (fname == "") {
errMsg += "First Name cannot be Empty\n";
}
if (lname == "") {
errMsg += "Last Name cannot be Empty\n";
}
if (dob == "") {
errMsg += "Date of Birth cannot be Empty\n";
}
if (email == "") {
errMsg += "Email cannot be Empty\n";
}
if ((genm == "") && (genf == "")) { //check whether gender is selected
errMsg += "A gender must be selected.\n";
}
if (saddress == "") {
errMsg += "Street Address cannot be Empty\n";
}
if (stown == "") {
errMsg += "Suburb or Town cannot be Empty\n";
}
if (pnumber == "") {
errMsg += "Phone Number cannot be Empty\n";
}
if (errMsg != "") {
alert(errMsg);
result = false;
}
return result;
}
function init() {
/* assign the <form> element to variable regForm */
var appForm = document.getElementById("appForm");
/* link function validate() to the onsubmit event of the form */
appForm.onsubmit = validate;
}
/* execute function init() once the window is loaded*/
window.onload = init;
<main>
<!-- Start of the form that the user fills out -->
<form method="post" action="http://mercury.swin.edu.au/it000000/formtest.php" id="appForm">
<h1>Job Application Form</h1>
<label for="jref">Job Reference Number</label><br>
<input type="text" name="jref" maxlength="5" id="jref" pattern="\d{4}" /><br>
<fieldset>
<label for="fname">First Name</label><br>
<input type="text" id="fname" maxlength="20" name="fname" /> <br>
<label for="lname">Last Name</label><br>
<input type="text" id="lname" maxlength="20" name="lname" /><br>
<label for="dob">Date of birth:</label><br>
<input id="dob" type="date" name="dob" /><br>
<label>Gender</label>
<input id="genm" type="radio" name="genm" value="Male" />
<label for="genm">Male</label>
<input id="genf" type="radio" name="genf" value="Female" />
<label for="genf">Female</label><br>
<label for="saddress">Street Address</label><br>
<input type="text" id="saddress" maxlength="40" name="saddress" /><br>
<label for="stown">Suburb/Town</label><br>
<input type="text" id="stown" maxlength="40" name="stown" /><br> State
<br>
<select name="slRank">
<option value="">Choose</option>
<option value="8">ACT</option>
<option value="8">ACT</option>
<option value="7">TAS</option>
<option value="6">SA</option>
<option value="5">WA</option>
<option value="4">NT</option>
<option value="3">QLD</option>
<option value="2">NSW</option>
<option value="1">VIC</option>
</select><br>
<label for="email">Email Address</label><br>
<input type="email" id="email" name="email" placeholder="example#gmail.com" /><br>
<label for="pnumber">Phone Number</label><br>
<input type="tel" id="pnumber" name="pnumber" placeholder="(##) ####-####" /><br> Skills
<select name="slRank">
<option value="">Choose</option>
<option value="9">Creativity</option>
<option value="8">Interpersonal Skills</option>
<option value="7">Critical Thinking</option>
<option value="6">Problem Solving</option>
<option value="5">Public Speaking</option>
<option value="4">Communication</option>
<option value="3">Collaboration</option>
<option value="2">Accounting</option>
<option value="1">Other</option>
</select><br /><br />
<label>Other Skills</label>
<br />
<textarea autofocus="autofocus" placeholder="Please fill out other skills you have here."></textarea><br>
<input type="submit" value="Apply" />
<input type="reset" value="Reset" />
</fieldset>
</form>
</main>
user this https://jqueryvalidation.org/ js library for form validation

Disable Submit button until all form fields are validated

I have a function to validate all fields, but I also want to disable the submit button until the fields are filled out AND validation is complete. What is the best way to go about doing this? I'm very new to JavaScript so very specific instructions/explanation is appreciated :)
function fieldValidation() {
var name = document.forms['RegForm']['Name'].value;
var address = document.forms['RegForm']['Address'].value;
var email = document.forms['RegForm']['EMail'].value;
var password = document.forms['RegForm']['Password'].value;
var telephone = document.forms['RegForm']['Telephone'].value;
var job = document.forms['RegForm']['Job'].value;
var comment = document.forms['RegForm']['Comment'].value;
var fullName = /^[a-zA-Z]+ [a-zA-Z]+$/;
var phnFormat = /((\(\d{3}\) ?)|(\d{3}-))?\d{3}-\d{4}/;
if (name === '') {
alert('Please enter your name.');
return false;
}
if (!fullName.test(name)) {
alert('Please make sure we have your full name.');
return false;
}
if (address === '') {
alert('Please enter your address.');
return false;
}
if (email === '') {
alert('Please enter your e-mail address.');
return false;
}
if (password === '') {
alert('Please enter a password.');
return false;
}
if (telephone === '') {
alert('Please enter your telephone number.');
return false;
}
if (!phnFormat.test(telephone)) {
alert('Please enter your phone number in the following format: (123) 555-1212)');
return false;
}
if (job.value === '') {
alert('Please select a job choice.');
return false;
}
if (comment.value === '') {
alert('Please enter a comment.');
return false;
}
return true;
}
<div class="container">
<main>
<form name="RegForm" action="/submit.php" onsubmit="return fieldValidation()" method="post">
<p>Name: <input type="text" size=65 name="Name" id="nameInput"> </p><br>
<p>Address: <input type="text" size=65 name="Address"> </p><br>
<p>E-mail Address: <input type="email" size=65 name="EMail"> </p>
<input type="checkbox" id="confirmApp" name="confirm">
<label for="confirmApp">I want to receive an email confirming my application.</label>
<br>
<p>Password: <input type="password" size=65 name="Password"> </p><br>
<p>Telephone: <input type="tel" size=65 name="Telephone"> </p><br>
<label for="jobChoice">Job Choice:</label>
<select name="Job" id="jobChoice">
<option value="">--- Select Job Choice ---</option>
<option value="IT">IT</option>
<option value="Human Resources">Human Resources</option>
<option value="Maintenance">Maintenance</option>
<option value="Management">Management</option>
<option value="Other">Other</option>
</select></p><br><br>
<p>Comments: <textarea cols="100" rows="10" name="Comment"> </textarea></p>
<p><input type="submit" value="send" name="Submit" id="submitBtn">
<input type="reset" value="Reset" name="Reset"></p>
</form>
</main>
</div>
You could do it in a couple of ways:
You could have a onclick="your validation function" for each input running your validation code.
Or you could add the required tag to each required input, this way the user cant submit the form unless every required field is filled in a.e. <input type="text" size="65" name="Name" id="nameInput"required>, however option two does not hide the submit button.
If you only want to disable the submission and not the submit button persé I'd suggest using the required tag for the relevant input fields.

Data Validation with "Select" Menu

A part of the application I am creating asks the user to enter the state of their current residence, it then asks the user to enter their postcode. The program then tests to see if the postcode is valid for that State.
Eg. State entered "VIC" postcode can't be >=4000 or < 3000
Instead of either receiving the error message or not, I constantly receive the error message even when the postcode is valid
JS for my WebPage
function validate () {
var result = true
var errMsg = " "
var postcode = document.getElementById("postcode").value;
var state = document.getElementById("state").value;
var other = document.getElementById("text").value;
if (state == "VIC" || postcode >= 4000 || postcode < 3000) {
errMsg = errMsg + "You have entered an invalid postcode for your chosen state\n"
result = false;
}
else if (state == "VIC" || postcode >=9000 || postcode < 8000) {
errMsg = errMsg + "You have entered an invalid postcode for your chosen state\n"
result = false;
}
else if (state == "NSW" || postcode >=3000 || postcode < 1000) {
errMsg = errMsg + "You have entered an invalid postcode for your chosen state\n"
result = false;
}
else if (state == "QLD" || postcode <4000 || postcode >= 5000) {
errMsg = errMsg + "You have entered an invalid postcode for your chosen stae\n"
result = false;
}
else if (state == "QLD" || postcode <9000 || postcode >= 10000) {
errMsg = errMsg + "You have entered an invalid postcode for your chosen state\n"
result = false;
}
else if (state == "NT" || postcode >= 1000) {
errMsg = errMsg + "You have entered an invalid postcode for your chosen state\n"
result = false;
}
else if (state == "WA" || postcode < 6000 || postcode >= 7000) {
errMsg = errMsg + "You have entered an invalid postcode for your chosen state\n"
result = false;
}
else if (state == "SA" || postcode < 5000 || postcode >= 6000) {
errMsg = errMsg + "You have entered an invalid postcode for your chosen state\n"
result = false;
}
else if (state == "TAS" || postcode < 7000 || postcode >= 8000) {
errMsg = errMsg + "You have entered an invalid postcode for your chosen state\n"
result = false;
}
else if (state == "ACT" || postcode >= 1000) {
errMsg = errMsg + "You have entered an invalid postcode for your chosen state\n"
result = false;
}
if (document.getElementById("other").checked = true || other == "If you selected Other, enter your answer here...") {
errMsg = errMsg + "You have selected other, please enter your answer into the text box provided"
result = false;
}
if (errMsg != "") {
document.getElementById("errMessage").value = errMsg;
}
return result;
}
function init() {
if (document.getElementById("applypage")!=null) {
var regForm = document.getElementById("regform");
job_apply();
regForm.onsubmit = validate;
}
else if (document.getElementById("jobspage") !=null) {
storeJobNumber();
}
}
window.onload = init;
HTML for my webPage
<!DOCTYPE html>
<html Lang="en">
<head>
<meta charset="utf-8" />
<meta name="description" content="CWA HELP DESK" />
<meta name="keywords" content="HTML, CWA, Help, Desk" />
<meta name="author" content ="Harry Keys" />
<title>Application Form</title>
<link href="style/style.css" rel="stylesheet" type="text/css">
<script src="apply.js"></script>
</head>
<body id="applypage">
<form id="regform" method="post" action="http://mercury.swin.edu.au/it000000/formtest.php" novalidate="novalidate">
<img src="images/logo.png" alt="Company Logo" />
<h1> Job Application Form </h1>
<fieldset>
<p><label for="jobNumber">Job Reference Number</label>
<input type="text" onkeyup="this.value=this.value.replace(/[^\d]/,'')" name="jobNumber" id="jobNumber" maxlength="5" size="7" required="required" readonly/>
</p>
<p><label for="givenName">Given Name</label>
<input type="text" onkeypress="return /[a-z]/i.test(event.key)" name="givenName" id="givenName" maxlength="20" size="15" required="required"/>
<label for="familyName">Family Name</label>
<input type="text" onkeypress="return /[a-z]/i.test(event.key)" name="familyName" id="familyName" maxlength="20" size="15" required="required"/>
</p>
</fieldset>
<fieldset>
<legend>Personal Details</legend>
<p><label for="dob">Date of Birth</label>
<input type="date" name="dob" id="dob" required="required"/>
</p>
<p><label for="staddress">Street Address</label>
<input type="text" name="staddress" id="staddress" maxlength="40" required="required"/>
<label for="suburb">Suburb/Town</label>
<input type="text" name="suburb" id="suburb" maxlength="40" required="required"/>
</p>
<p><label for="state">State</label>
<select name="state" id="state">
<option value="Please Select">Please Select</option>
<option value="VIC">VIC</option>
<option value="NSW">NSW</option>
<option value="QLD">QLD</option>
<option value="NT">NT</option>
<option value="WA">WA</option>
<option value="SA">SA</option>
<option value="TAS">TAS</option>
<option value="ACT">ACT</option>
</select>
</p>
<p><label for="postcode">Postcode</label>
<input type="text" name="postcode" id="postcode" onkeyup="this.value=this.value.replace(/[^\d]/,'')" maxlength="4" size="4" required="required"/>
</p>
<p><label for="email">Email</label>
<input type="email" name="email" id="email" required="required"/>
</p>
<p><label for="phonenumber">Phone Number</label>
<input type="text" name="phonenumber" id="phonenumber" onkeyup="this.value=this.value.replace(/[^\d]/,'')" maxlength="12" size="12" required="required"/>
<fieldset>
<legend>Gender</legend>
<p> <label for="male">Male</label>
<input type="radio" id="male" name="Gender" value="male" required="required"/>
<label for="female">Female</label>
<input type="radio" id="female" name="Gender" value="female"/>
<label for="other">Other</label>
<input type="radio" id="undefined" name="Gender" value="undefined"/>
</p>
</fieldset>
<fieldset>
<legend>Skills List</legend>
<p> <label for="teamwork">Teamwork</label>
<input type="checkbox" id="teamwork" name="Skill[]" value="Teamwork" checked="checked"/>
<label for="rubyskills">Ruby Experience</label>
<input type="checkbox" id="rubyskills" name="Skill[]" value="Rubyskills"/>
<label for="efficiency">Efficiency</label>
<input type="checkbox" id="efficiency" name="Skill[]" value="Efficiency"/>
<label for="communication">Communication</label>
<input type="checkbox" id="communication" name="Skill[]" value="Communication"/>
<label for="other">Other</label>
<input type="checkbox" id="other" name="Skill[]" value="other"/>
</p>
<p> <textarea id="text" name="Skill[]" rows="5" cols="20" placeholder="If you selected Other, enter your answer here..."></textarea>
</p>
</fieldset>
</fieldset>
<p> <textarea id="errMessage" rows="3" cols="40"></textarea> </p>
<input type="submit" value="Submit"/>
<input type="reset" value="Reset Form"/>
</form>
When I select "NSW" and enter a postcode that is not >=3000 or <1000 I should not receive an error. But I still do
I think your if-else-if construct is a little bit confusing.
I'd recommend a switch-block to validate which state has been chosen and with each case check if the postcode is in the correct range.
Something like:
function validate() {
var result = true
var errMsg = " "
var postcode = document.getElementById("postcode").value;
var state = document.getElementById("state").value;
var other = document.getElementById("text").value;
switch (state) {
case "VIC":
if (postcode >= 3000 && postcode < 4000) {
result = true;
}
break;
case "NSW":
if (postcode >= 1000 && postcode < 3000) {
result = true;
}
break;
case "QLD":
if (postcode >= 4000 && postcode < 5000) {
result = true;
}
break;
}
if (!result) {
errMsg = errMsg + "You have entered an invalid postcode for your chosen state\n";
}
if (document.getElementById("other").checked = true || other == "If you selected Other, enter your answer here...") {
errMsg = "You have selected other, please enter your answer into the text box provided"
result = false;
}
if (errMsg != "") {
document.getElementById("errMessage").value = errMsg;
}
return result;
}

How would it be possible to call multiple js functions to a single form?

Now when I run this code, the form's function do not run. Why, Im not sure. Is it because of the doall() function I placed in my js. I did it specifically to tell the button tag thats the function to ultimately run. Is placing functions within 1 whole function considered bad? Where did I go wrong with my javascript and html pairings? I am ultimately trying to have one part of the form validate with alerts, have the total spit a given value automatically after a radio is chosen, and as you click the submit button after everything is filled, it creates that var sign.
<form name="form1" action="" onsubmit="return doall{};">
<label for="fname">First Name:</label>
<input type="text" name="fname" id="fname" size="12" placeholder="First Name">
<label for="lname">Last Name:</label>
<input type="text" name="lname" id="lname" size="12" placeholder="Last Name">
<label for="address">Address:</label>
<input type="text" name="address" id="address" size="40" placeholder="Address">
<label for="city">City:</label>
<input type="text" name="city" id="city" size="40" placeholder="City">
<label for="state">State:</label>
<input type="text" name="state" id="state" size="40" placeholder="State">
<label for="country">Country:</label>
<input type="text" name="country" id="country" size="40" placeholder="Country">
<label for="zipcode">Zip Code:</label>
<input type="text" name="zipcode" id="zipcode" placeholder="Zip Code">
<p><label for="email">Email:</label>
<input type="text" name="email" id="email" size="30" placeholder="Email Address"></p>
<label for="password">Password:</label>
<input type="password" name="password" id="password" size="20" placeholder="Password">
<p><label for="repass">Retype Password:</label>
<input type="password" name="repass" id= "repass" size="20" placeholder="Re-type Password"></p>
<p><b>Choose the Program you would like to purhase:</b></p>
<table align ="center">
<tr>
<td><input type="radio" name="offers" value= "Basic" id="chkbox" onchange="ontotal()"></td>
<td>Basic</td>
<td>$<span>19.99</span></td>
</tr>
<tr>
<td><input type="radio" name="offers" value= "Premium" id="chkbox" onchange="ontotal()" ></td>
<td>Premium</td>
<td>$<span >35.99</span></td>
</tr>
<tr>
<td><input type="radio" name="offers" value= "Super" id="chkbox" onchange="ontotal()"></td>
<td>Super</td>
<td>$<span >59.99</span></td>
</tr>
</table>
<p>
Total:
<input type="text" id="prototal" size="8" value="0" >
</p>
</form>
<button type="button" onclick="doall();">Submit</button>
<p id="submit"></p>
` function formval() {
var first = document.getElementById("fname")
var second = document.getElementById("lname")
var third = document.getElementById("address")
var fourth = document.getElementById("city")
var fifth = document.getElementById("state")
var sixth = document.getElementById("country")
var seventh = document.getElementById("zipcode")
var fire = document.getElementById("email")
var sense = document.getElementById("password")
var retype = document.getElementById("repass")
if (first == ""){
alert("Please enter first name");
return false;
}
if (second == ""){
alert("Please enter last name");
return false;
}
if (third == ""){
alert("Please enter address");
return false;
}
if(fourth == ""){
alert("Please enter city");
return false;
}
if (fifth == ""){
alert("Please enter state");
return false;
}
if (sixth == ""){
alert("Please enter county");
return false;
}
if (seventh == ""){
alert("Please enter zip code");
return false;
}
if (fire == ""){
alert("Please enter email address");
return false;
}
if (sense == ""){
alert("Please enter a password");
return false;
}
if (retype == ""){
alert("Please enter your typed password");
return false;
}
var sign = "Thank you for submission. Your purchase order instructions will be emailed shortly!";
document.getElementById("sub").innerHTML = sign;
}
var programprices = new Array();
programprices["Basic"]=19.99;
programprices["Premium"]=35.99;
programprices["Super"]=59.99;
function ontotal(){
var producttotal=0;
var calform = document.forms["form1"]
var offers = calform.elements["offers"]
for(var i = 0; i < offers.length; i++)
{
if (offers[i].checked)
{
producttotal = programprices[offers[i].value];
break;
}
}
return producttotal;
}
function caltotal(){
var price = ontotal;
var presentme = document.getElementById('prototal')
presentme.innerHTML = price
}
function doall(){
formval();
ontotal();
caltotal();
}
var form = document.getElementById('form1');
form.addEventListener('submit', formval);
form.addEventListener('submit', ontotal);
form.addEventListener('submit', caltotal); `
https://jsfiddle.net/Lnehnkaz/
First correct the above mentioned errors.
There is nothing wrong with calling some functions from another function. If you want multiple submit handlers, put the submit button within the form, change it to type="submit" and use the addEventListener method.
This works, when you give the form the attribute id="form1":
var form = document.getElementById('form1');
form.addEventListener('submit', formval);
form.addEventListener('submit', ontotal);
form.addEventListener('submit', caltotal);

Validating a form with JavaScript and displaying them on the page rather than an alert box

I've created a form, that I need to validate with JavaScript or using Jquery. How would I validate if the dropdown list has the value "Title" and if the text box is empty and display it on the page rather then an alert box :
<form action="" method="post" accept-charset="UTF-8" name="myForm">
<option value="Title" id="title_3-0" disabled selected>Title</option><option value="Mr" id="title_3-1">Mr</option>
<option value="Mrs" id="title_3-2">Mrs</option><option value="Miss" id="title_3- 3">Miss</option>
<option value="Ms" id="title_3-4">Ms</option><option value="Dr" id="title_3-5">Dr</option>
<option value="Professor" id="title_3-6">Professor</option></select></div></div>
TextBox:
<input type="text" class="text" name="firstname_4" id="amf-input-firstname_4" value="" placeholder="First Name">
I also have a button.
Here is a start:
<script>
function validateForm()
{
var return_value = true;
var x=document.forms["myForm"]["firstname_4"].value;
if (x==null || x=="")
{
document.getElementById("error").innerHTML += "First name must be filled out<br />";
return_value = false;
}
var y=document.forms["myForm"]["selectid"];
if(y.options[y.selectedIndex].value == "Title")
{
document.getElementById("error").innerHTML += "You need to select a title<br />";
return_value = false;
}
return return_value;
}
</script>
<span id="error"></span>
<form name="myForm" onsubmit="return validateForm()" method="post">
First name: <input type="text" class="text" name="firstname_4" id="amf-input-firstname_4" value="" placeholder="First Name">
<input type="submit" value="Submit">
</form>
If you like, you can also put an "error span element" above/beneath each field and set each error individually:
<script>
function validateForm()
{
var return_value = true;
var x=document.forms["myForm"]["firstname_4"].value;
if (x==null || x=="")
{
document.getElementById("error1").innerHTML = "First name must be filled out";
return_value = false;
}
var y=document.forms["myForm"]["selectid"];
if(y.options[y.selectedIndex].value == "Title")
{
document.getElementById("error2").innerHTML = "You need to select a title";
return_value = false;
}
return return_value;
}
</script>
<form name="myForm" onsubmit="return validateForm()" method="post">
First name: <input type="text" class="text" name="firstname_4" id="amf-input-firstname_4" value="" placeholder="First Name">
<span id="error1"></span>
Title: <input .... >
<span id="error2"></span>
<input type="submit" value="Submit">
</form>
Since you are new to this, look up these links and read up. It will guide you through it. That's better than us giving you all the code. Because this kind of form validation is important and hence you better learn it from scratch.
Link-1
Link-2
Link-3 (using library)
Html:
<select id="ddl"> <option value="Title" id="title_3-0" selected>Title</option><option value="Mr" id="title_3-1">Mr</option>
<option value="Mrs" id="title_3-2">Mrs</option><option value="Miss" id="title_3- 3">Miss</option>
<option value="Ms" id="title_3-4">Ms</option><option value="Dr" id="title_3-5">Dr</option>
<option value="Professor" id="title_3-6">Professor</option></select>
<input type="text" class="text" name="firstname_4" id="amf-input-firstname_4" value="" placeholder="First Name">
<input type="button" value="Submit" id="btn"/>
<span id="error"/>
JQuery:
$('#btn').click(function (){
if(($('#amf-input-firstname_4').val()=='') || ($("#ddl :selected").val() == 'Title'))
{
$('#error').html('Please select title and enter name.');
}
else
{
$('#error').html('Success');
}
return false;
});
Demo:
http://jsfiddle.net/8h8HF/

Categories