i am creating a website using django, i have added a little js for validation, but it's not working. whenever i run the code it says
TypeError: document.getElementById(...) is null
html snippet
<form onsubmit=" return validate_bus()" action="confirm_bus/{{busname}}" method="post">
{% csrf_token %}
<div id="left">
<label>Departure date</label>
<input type="date" autocomplete="off" name="date" id="departuredate"> <br><br>
<label>Username</label>
<input type="text" name="username" id="BusUsername" autocomplete="off">
</div>
<div id="right">
<label>Number of seats</label><br>
<select autocomplete="off" name="seats" >
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
<br>
</select><br><br>
<label> password</label>
<input type="password" autocomplete="off" name="password" id="password">
</div>
<label id="error_message">{{error_message}}</label><br>
<button type="submit">Confirm booking</button>
</form>
and this is my js snippet
function validate_bus()
{
var date = document.getElementById("departuredate").value;
var username = document.getElementById("BusUsername").value;
var seats = document.getElementById("seats").value;
var password = document.getElementById("password").value;
var date_regx = /^(19|20)\d\d([- /.])(0[1-9]|1[012])\2(0[1-9]|[12][0-9]|3[01])$/
var username_regx = /^[a-zA-Z0-9_$.#]+$/
var password_regx = /^(?=.*\d).{4,12}$/
var seats_regx = /[1-6]{1}/
var valid = true
console.log(date, username, seats, password);
if (! date_regx.test(date))
{
valid = false;
}
if (! username_regx.test(username))
{
valid = false;
}
if (! seats_regx.test(seats))
{
valid = false;
}
if(! password_regx.test(password))
{
valid = false;
}
if (!valid)
{
var error = document.getElementById("error_message").innerHTML = "invalid input";
}
console.log(valid)
return valid;
};
Hi there in your var seats = document.getElementById("seats").value; calls an id that's doesn't exist.
Just add the id to your select element and it should fix your error.
ex:
<select autocomplete="off" id="seats" name="seats" >
Related
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
Why isn't this function storing variables and why isn't it validating the first name? It won't work for some reason. There are no error messages in the console when I open the website. Please help, this is very annoying and I've been struggling with this for a while. Is there something going past the error messages that are stopping my JavaScript code from working?
"use strict";
function validate() {
var errMsg = "";
var result = true;
// get variables from form and check rules
// if something is wrone set result to false and add error message
var fname = document.getElementById("fname").value; //validates first name
if (!fname.match(/^[a-zA-Z]+$/)) {
errMsg += "Please enter your first name (Only alpha characters).\n";
result = false;
}
/*get variables from form and check rules*/
var postcode = document.getElementById("postcode").value;
var state = document.getElementById("state").options[
document.getElementById("state").selectedIndex
].text;
var regex;
//VIC = 3 OR 8, NSW = 1 OR 2 ,QLD = 4 OR 9 ,NT = 0 ,WA = 6 ,SA=5 ,TAS=7 ,ACT= 0.
switch (state) {
case "Please Select":
return false;
case "VIC":
regex = new RegExp(/(3|8)\d+/);
break;
case "NSW":
regex = new RegExp(/(1|2)\d+/);
break;
case "QLD":
regex = new RegExp(/(4|9)\d+/);
break;
case "NT":
regex = new RegExp(/0\d+/);
break;
case "WA":
regex = new RegExp(/6\d+/);
break;
case "SA":
regex = new RegExp(/5\d+/);
break;
case "TAS":
regex = new RegExp(/7\d+/);
break;
case "ACT":
regex = new RegExp(/0\d+/);
break;
}
if (!postcode.match(regex)) {
errMsg = errMsg + "State and postcode do not match\n";
result = false;
}
if (errMsg) {
alert(errMsg);
}
if (result) {
storeBooking(
fname,
lname,
email,
phone,
streetname,
suburb,
state,
postcode,
productquantity
);
}
return result;
}
function storeBooking(
fname,
lname,
email,
phone,
streetname,
suburb,
state,
postcode,
productquantity
) {
sessionStorage.fname = fname;
sessionStorage.lname = lname;
sessionStorage.email = email;
sessionStorage.phone = phone;
sessionStorage.streetname = streetname;
sessionStorage.suburb = suburb;
sessionStorage.state = state;
sessionStorage.postcode = postcode;
sessionStorage.productquantity = productquantity;
}
// this stores values inside of sessionStorage
function init() {
var regForm = document.getElementById("regform"); // get ref to the HTML element
regForm.onsubmit = validate; //register the event listener
}
window.onload = init;
<!DOCTYPE html>
<html lang="en">
<head>
<script src="scripts/part2.js"></script>
<title>SwinTech</title>
<link rel="stylesheet" type="text/css" href="css/style.css">
</head>
<body class="enquiriespage">
<header>
<div class="main">
<div class="logo">
<img src="logo.png" alt="logo">
</div>
<ul>
<li>Home</li>
<li>Products</li>
<li class="active">Enquiries</li>
<li>About</li>
</ul>
</div>
</header>
</body>
<section class="enquirything">
<div class="containerr">
<form action="payment.html" id="regform" method="post">
<label for="fname">First Name</label>
<input type="text" id="fname" name="fname" required="required" placeholder="Your name.." maxlength="25" onkeypress="return (event.charCode > 64 && event.charCode < 91) || (event.charCode > 96 && event.charCode < 123) || (event.charCode==32)">
<label for="lname">Last Name</label>
<input type="text" id="lname" name="fname" required="required" placeholder="Your last name.." onkeypress="return (event.charCode > 64 && event.charCode < 91) || (event.charCode > 96 && event.charCode < 123) || (event.charCode==32)">
<label for="email">Email Address</label>
<br>
<br>
<input type="email" id="email" name="emailadd" required="required" placeholder="Your email address..">
<br>
<br>
<label for="phone">Phone Number</label>
<br>
<br>
<input type="text" id="phone" name="txtChar" required="required" placeholder="e.g. 0451124561" maxlength="10">
<br>
<br>
<h1>Address</h1>
<br>
<label for="streetname">Street Address</label>
<input type="text" id="streetname" name="streetname" required="required" placeholder="Your street name..." maxlength="40"/>
<label for="suburb">Suburb/Town</label>
<input type="text" id="suburb" name="suburb" required="required" placeholder="Your suburb/town..." maxlength="40">
<label for="state">Choose a state:</label>
<br>
<select name="state" id="state" required="required">
<option value="">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>
<br>
<label for="postcode">Postcode</label>
<input type="text" id="postcode" name="postcode" required="required" placeholder="Your postcode..." maxlength="4" minlength="4" pattern="^[0-9]{4}$">
<fieldset>
<br>
<h1>Product Selection</h1>
<br>
<label for="productselection">Please select the product:</label>
<br>
<select id="productselection" name="Product" >
<option value="none">Please Select a Product</option>
<option value="Workstation-Laptop">Workstation Laptop</option>
<option value="Gaming-Laptop">Gaming Laptop</option>
<option value="Laptop-Stand">Laptop Stand</option>
<option value="Office-Laptop">Office Laptop</option>
</select>
<br>
<h1>Amount of Product:</h1>
<section>
<br>
<input type="number" id="productquantity" />
<br>
</section>
</fieldset>
<br>
<input type="submit" value="Pay Now"> <input type="reset" value="Reset" />
</fieldset>
</form>
</div>
</section>
<div class="footer">
<div class="footer-content"></div>
<div class="footer-bottom"></div>
© swintech.com | Designed by Bilal El-leissy
</div>
</html>
The code looks fine, but judging by this code, I'm taking a stab in the dark and saying you're hitting a security error, likely due to not serving the file, and using file:// in the browser instead of http[s]:// . You can see the proper error if you halt the code from completing the submit.
function validate(event) {
event.preventDefault();
From MDN:
The request violates a policy decision, or the origin is not a valid scheme/host/port tuple (this can happen if the origin uses the file: or data: scheme, for example). For example, the user may have their browser configured to deny permission to persist data for the specified origin.
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();
}
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 :)
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/