Validation form with JavaScript - javascript

I'm trying to create a form validation, in pure JavaScript.
I have two elements to validate, a select option and a checkbox, but I can't manage to make the select-option to work.
This is the first time I try this, please be patient:
var registrationForm, elSelectGender, elGenderHint, elTerms, elTermsHint; // Declare variables
registrationForm = document.getElementById('registrationForm'); // Store elements
elSelectGender = document.getElementById('gender');
elGenderHint = document.getElementById('genderHint');
elTerms = document.getElementById('terms');
elTermsHint = document.getElementById('termsHint');
elName = document.getElementById('firstName');
elNameHint = document.getElementById('nameHint');
function checkName(event) {
if (elSelectGender.valueOf() == null) { // If name not entered
elNameHint.innerHTML = 'You must insert your name.'; // Show message
event.preventDefault(); // Don't submit form
}
}
function checkGender(event) {
if (elSelectGender.valueOf() == 'Select an option:') { // If gender not selected
elGenderHint.innerHTML = 'You must select a gender.'; // Show message
event.preventDefault(); // Don't submit form
}
}
function checkTerms(event) {
if (!elTerms.checked) { // If check-box ticked
elTermsHint.innerHTML = 'You must agree to the terms.'; // Show message
event.preventDefault(); // Don't submit form
}
}
//Create event listeners: submit calls checkTerms(), change calls packageHint()
registrationForm.addEventListener('submit', checkName, false);
registrationForm.addEventListener('submit', checkGender, false);
registrationForm.addEventListener('submit', checkTerms, false);
<!DOCTYPE HTML>
<html>
<form id="registrationForm" name="registrationForm" method="post" action="example.html">
<div>
<label for="firstName" class="input"> Name: </label>
<input name="firstName" class="form-control" id="firstName" placeholder="First Name" type="text" />
<div id="nameHint" class="warning"></div>
</div>
<div>
<label for="gender" class="selectbox"> Gender: </label>
<select id="gender">
<option value="Select an option:">Select an option:</option>
<option value="Male">Male</option>
<option value="Female">Female</option>
<option value="I prefer not to say">I prefer not to say</option>
</select>
<div id="genderHint" class="warning"></div>
</div>
<div>
<input type="checkbox" id="terms" />
<label for="terms" class="checkbox"> Check to agree to terms & conditions</label>
<div id="termsHint" class="warning"></div>
</div>
<input class="btn btn-primary" id="submitButton" type="submit" value="Sign up for G Holiday" />
</form>
</html>
I expect to have a warning message and validation for all three elements. If one of the three elements is not validated, it shouldn't go to the next page.
It only works for the checkbox for some reason, the other two elements are ignored.

I'd wrap the selects and inputs into label and use CSS to display the .warning error messages.
Than I'd use Array.prototype.some() to check for any of my elements does not passes a check to than use ev.preventDefault() and display the warnings:
const EL = sel => document.querySelector(sel),
warning = (el, err) => [err, el.closest('label').classList.toggle('is-error', err)][0],
noValue = el => warning(el, !el.value.trim()),
noCheck = el => warning(el, !el.checked),
checkFormRegistration = ev => {
const isSomeInvalid = [
noValue(EL('#firstName')),
noValue(EL('#gender')),
noCheck(EL('#terms'))
].some(b => b);
if (isSomeInvalid) ev.preventDefault();
};
EL('#registrationForm').addEventListener('submit', checkFormRegistration);
label.is-error > *{
outline: 1px solid red;
outline-offset: -1px;
}
label + .warning {
display: none;
color: red;
}
label.is-error + .warning {
display: block;
}
<form id="registrationForm" name="registrationForm" method="post" action="example.html">
<div>
<label> Name:
<input name="firstName" class="form-control" id="firstName" placeholder="First Name" type="text">
</label>
<div class="warning">Please, enter a name</div>
</div>
<div>
<label> Gender:
<select id="gender">
<option value="">Select an option:</option>
<option value="Male">Male</option>
<option value="Female">Female</option>
<option value="I prefer not to say">I prefer not to say</option>
</select>
</label>
<div class="warning">Please, select a gender</div>
</div>
<div>
<label>
<input type="checkbox" id="terms">
Check to agree to terms & conditions
</label>
<div class="warning">You must agree to the terms</div>
</div>
<input class="btn btn-primary" id="submitButton" type="submit" value="Sign up for G Holiday">
</form>

I changed valueOf() to value equal to empty (when form is initialized, the field is empty, it is not null).
Make sure that your HTML elements are correct, I saw it was wrong before, now it seems to have been corrected.
I added an else statement to handle the errors in the case where the user corrects the validation errors.
Still, this is quite a simplification of validation, it takes a lot more work (things like min-length, max-length you might want to consider them too, as well as sanitization, trimming as mentioned by some commenters, which I will leave it to you).
var registrationForm, elSelectGender, elGenderHint, elTerms, elTermsHint; // Declare variables
registrationForm = document.getElementById('registrationForm'); // Store elements
elSelectGender = document.getElementById('gender');
elGenderHint = document.getElementById('genderHint');
elTerms = document.getElementById('terms');
elTermsHint = document.getElementById('termsHint');
elName = document.getElementById('firstName');
elNameHint = document.getElementById('nameHint');
function checkName(event) {
if (elName.value == '') { // If name not entered
elNameHint.innerHTML = 'You must insert your name.'; // Show message
event.preventDefault(); // Don't submit form
} else {
elNameHint.innerHTML = '';
}
}
function checkGender(event) {
if (elSelectGender.value == 'Select an option:') { // If gender not selected
elGenderHint.innerHTML = 'You must select a gender.'; // Show message
event.preventDefault(); // Don't submit form
} else {
elGenderHint.innerHTML = '';
}
}
function checkTerms(event) {
if (!elTerms.checked) { // If check-box ticked
elTermsHint.innerHTML = 'You must agree to the terms.'; // Show message
event.preventDefault(); // Don't submit form
} else {
elTermsHint.innerHTML = '';
}
}
//Create event listeners: submit calls checkTerms(), change calls packageHint()
registrationForm.addEventListener('submit', checkName, false);
registrationForm.addEventListener('submit', checkGender, false);
registrationForm.addEventListener('submit', checkTerms, false);
<!DOCTYPE HTML>
<html>
<form id="registrationForm" name="registrationForm" method="post" action="example.html">
<div>
<label for="firstName" class="input"> Name: </label>
<input name="firstName" class="form-control" id="firstName" placeholder="First Name" type="text" />
<div id="nameHint" class="warning"></div>
</div>
<div>
<label for="gender" class="selectbox"> Gender: </label>
<select id="gender">
<option value="Select an option:">Select an option:</option>
<option value="Male">Male</option>
<option value="Female">Female</option>
<option value="I prefer not to say">I prefer not to say</option>
</select>
<div id="genderHint" class="warning"></div>
</div>
<div>
<input type="checkbox" id="terms" />
<label for="terms" class="checkbox"> Check to agree to terms & conditions</label>
<div id="termsHint" class="warning"></div>
</div>
<input class="btn btn-primary" id="submitButton" type="submit" value="Sign up for G Holiday" />
</form>
</html>

Related

Activate textbox on change of an item in Drop down in HTML

I am trying to do the following:
I have drop down menu with four options in it. When I choose Shipped a text box should enabled. So I tried the following:
<div class="col-md-3">
<select class="form-control" id="ostatus" name= "ostatus">
<option value="Uploaded" <?php if ($dispatch_status == "Uploaded") echo "selected='selected'";?> >Uploaded</option>
<option value="Processing" <?php if ($dispatch_status == "Processing") echo "selected='selected'";?> >Processing</option>
<option value="Dispatched" <?php if ($dispatch_status == "Dispatched") echo "selected='selected'";?> >Dispatched</option>
<option value="Shipped" <?php if ($dispatch_status == "Shipped") echo "selected='selected'";?> >Shipped</option>
</select>
</div>
</div>
<input type="text" class="form-control" name="shipping_notes" disabled="true" id="shipping_notes" aria-describedby="" placeholder="Enter Shipping details">
Java script:
<head>
<script type="text/javascript">
document.getElementById('ostatus').addEventListener('change', function()
{
console.log(this.value);
if (this.value == 'Shipped') {
document.getElementById('shipping_notes').disabled = false;
} else {
document.getElementById('shipping_notes').disabled = true;
}
});
</script>
</head>
Doesn't seem to trigger? I don't see log on console too. What could be wrong here?
Update:
I have pasted the html code here:
https://justpaste.it/6zxwu
Update
Since you've now shared your other code I think I know what you want. You have multiple modals, each with a select list and shipping_notes textbox which should be enabled when the selection is Shipped for that particular modal. I've modified your HTML to get this working.
I've updated your HTML a bit. You have multiple elements with the same ID. HTML IDs should be unique. If you want to target multiple elements it's safer to use class (or data-) attributes. I've added class="order-status" to each select and class="shipping_notes_txt" to each textbox. I've used element.querySelector() and document.querySelectorAll() to select DOM elements.
The snippet below mimics two modals. When the select is updated, it only enables/disabled the textbox within the same form element.
// wait for the DOM to load
document.addEventListener('DOMContentLoaded', function() {
// get all select elements with class=order-status
var selects = document.querySelectorAll('.order-status');
// iterate over all select elements
for (var i = 0; i < selects.length; i++) {
// current element
var element = selects[i];
// add event listener to element
element.addEventListener('change', function()
{
console.log(this.value);
// get the form closest to this element
var form = this.closest('form');
// find the shipping notes textbox inside form and disable/enable
if (this.value == 'Shipped') {
form.querySelector('.shipping_notes_txt').disabled = false;
} else {
form.querySelector('.shipping_notes_txt').disabled = true;
}
});
// default value if status == Shipped: enable textbox
if (element.value == "Shipped")
{
var form = element.closest('form');
form.querySelector('.shipping_notes_txt').disabled = false;
}
}
});
.modal1 {
display:inline-block;
vertical-align:top;
padding: .5em;
padding-bottom:5em;
border: 1px solid black;
}
<div class="modal1">
<h3>First Modal</h3>
<div id="edit1" class="modal fade" role="dialog">
<form action="order.php" autocomplete="off" method="post">
<div class="col-md-2 ml-3 pt-1">
<label for="role" class="mr-3">Status</label>
</div>
<select class="form-control order-status" id="ostatus1" name= "ostatus">
<option value="Uploaded" selected='selected' >Uploaded</option>
<option value="Processing">Processing</option>
<option value="Dispatched">Dispatched</option>
<option value="Shipped">Shipped</option>
</select>
<input type="text" class="form-control shipping_notes_txt" name="shipping_notes" disabled="true" id="shipping_notes1" aria-describedby="emailHelp" placeholder="Enter Shipping details">
</form>
</div>
</div>
<div class="modal1">
<h3>Second Modal</h3>
<div id="edit20" class="modal fade" role="dialog" >
<form action="order.php" autocomplete="off" method="post">
<div class="col-md-2 ml-3 pt-1">
<label for="role" class="mr-3">Status</label>
</div>
<select class="form-control order-status" id="ostatus20" name= "ostatus">
<option value="Uploaded" >Uploaded</option>
<option value="Processing">Processing</option>
<option value="Dispatched">Dispatched</option>
<option value="Shipped" selected='selected' >Shipped</option>
</select>
<input type="text" class="form-control shipping_notes_txt" name="shipping_notes" disabled="true" id="shipping_notes20" aria-describedby="emailHelp" placeholder="Enter Shipping details">
</form>
</div>
</div>
Add onchange to your <select>
<select class="form-control" id="ostatus" name= "ostatus" onchange = "statuschange()">
And change the JavaScript to :
<script type="text/javascript">
function statuschange(){
var drpDownValue = document.getElementById('ostatus').value;
if (drpDownValue == 'Shipped')
{
document.getElementById('shipping_notes').disabled = false;
}
else
{
document.getElementById('shipping_notes').disabled = true;
}
}
</script>
assuming everything on the server side this works HTML comes first
<div class="col-md-3"> <select class="form-control" id="ostatus" name= "ostatus">
<option value="Uploaded" selected="selected" >Uploaded</option>
<option value="Processing" >Processing</option>
<option value="Dispatched" >Dispatched</option>
<option value="Shipped" >Shipped</option>
</select>
</div>
</div>
<input type="text" class="form-control" name="shipping_notes" disabled="true" id="shipping_notes" aria-describedby="" placeholder="Enter Shipping details">
document.getElementById('ostatus').addEventListener('change', function()
{
console.log(this.value);
if (this.value == 'Shipped') {
document.getElementById('shipping_notes').disabled = false;
} else {
document.getElementById('shipping_notes').disabled = true;
}
});

How not to open a window if the form fields are not filled?

I have this submit button on my form with a jQuery action to open a window depending on the users choice. However, I just want the window to open if the fields are filled. I have this code and I want to merge it with an if.
$(function() {
$('#chkveg').multiselect({
includeSelectAllOption: true
});
$('#btnget').click(function() {
window.open($('#chkveg').val());
})
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form action="http://formmail.kinghost.net/formmail.cgi" method="POST">
<input name="nome" type="text" class="nome" id="nome" required width="100%" placeholder="Nome:">
<input name="cpf" type="text" class="cpf" id="cpf" placeholder="CPF:">
<div style="clear:both"></div><br/>
<input name="nascimento" type="text" class="nascimento" id="nascimento" placeholder="Data de nascimento:">
<select id="chkveg">
<option value="https://pag.ae/7ULKPL7TH">Associados Ancord + C.Dados = R$700,00</option>
<option value="https://pag.ae/7ULKQ8Zm2">Associados Ancord = R$800,00</option>
<option value="https://pag.ae/7ULKQLB9m">Associados Entidades Apoiadoras + C.Dados = R$800,00</option>
</select>
<input id="btnget" class="submit-btn" type="submit" value="INSCREVER-SE">
</form>
For exemple:
IF (#FORM).REQUIRED = TRUE {
(#BUTTON).WINDOWOPEN
}
Thanks
Because you using a submit button you will need to return false, in case if you don't want to do anything. Before that, you need also to check if your required field are empty or not. (i.e. $(your field).val() === "" then it's empty, if all you need have, then call the window.open() function.
Note: you can merge multiple fields for checking ie: $(".your_field1, .your_field2, .your_field3").val() === "" however this is an OR operation.
One possible solution:
$(function() {
$('#btnget').click(function() {
let isEmpty = false;
$('#data_form input,textarea,select').filter(':visible').each(function(i) {
if ($(this).val() === "") {
isEmpty = true;
return false;
}
});
if (isEmpty) {
return false;
}
window.open($('#chkveg').val());
})
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form id="data_form" action="http://formmail.kinghost.net/formmail.cgi" method="POST">
<input name="nome" type="text" class="nome" id="nome" required width="100%" placeholder="Nome:">
<input name="cpf" type="text" class="cpf" id="cpf" placeholder="CPF:">
<div style="clear:both"></div><br/>
<input name="nascimento" type="text" class="nascimento" id="nascimento" placeholder="Data de nascimento:">
<select id="chkveg">
<option value="https://pag.ae/7ULKPL7TH">Associados Ancord + C.Dados = R$700,00</option>
<option value="https://pag.ae/7ULKQ8Zm2">Associados Ancord = R$800,00</option>
<option value="https://pag.ae/7ULKQLB9m">Associados Entidades Apoiadoras + C.Dados = R$800,00</option>
</select>
<input id="btnget" class="submit-btn" type="submit" value="INSCREVER-SE">
</form>
If you want only for the required fields, than use filter('[required]:visible') instead of filter(':visible').

How to use a checkbox to show more options of a form and change the action attribute of the form?

Hi I am creating a website that has a form to search rooms. I wanted to make it so a checkbox, when clicked, show new options AND change the action ="" attribute of the form.
<form class="form-horizontal" action="reservation?action=listRooms" method="POST">
<label for="">Date </label>
<div class="datepicker ll-skin-nigran hasDatepicker">
<input class="form-control" type="text" placeholder="14/03/2016" name="dateReservation" id="date" required="required"/>
</div>
<br />
<div>
<input type="checkbox" name="choice-for" id="choice-form">
<label for="choice-for">Show More Options.</label>
<div class="reveal-if-active">
<label for="">Slots</label>
<select name="slot" name ="slot" id="slot" >
<option value="">Choose a slot </option>
<option value="8h-9h30">8h00-9h30</option>
<option value="9h30-11h">9h30-11h00</option>
<option value="11h-12h30h">11h00-12h30h</option>
<option value="12h30-14h">12h30-14h00</option>
<option value="14h-15h30">14h00-15h30</option>
<option value="15h30-17h">15h30-17h00</option>
<option value="17h-18h30">17h00-18h30</option>
</select>
<br />
<label for="">Display Screens</label>
<input class="form-control" type="text" placeholder=" 26 pouces" name="screen" id="screen" />
<br />
<label for="">CPU</label>
<input class="form-control" type="text" placeholder="Intel Core i5 " name="processor" id="processor" />
<br />
<label for="">RAM</label>
<input class="form-control" type="text" placeholder=" 2Go de RAM ?" name="ram" id="ram" />
<br />
<input type="submit" value="Réserver" class="btn btn-primary" />
</div>
I tried then to use a javascript(JQuery) script to satisfy my expectations:
<script>
$(function() {
$( "#date" ).datepicker({ dateFormat: 'dd/mm/yy' });
});
$("#choice-form").change(function() {
//there i need to know when the checkbox is changed dynamically so the attribute can change too.
$("#form-horizontal).attr("reservation?action=listRooms");
});
var FormStuff = {
init: function() {
this.applyConditionalRequired();
this.bindUIActions();
},
bindUIActions: function() {
$("input[type='radio'], input[type='checkbox']").on("change", this.applyConditionalRequired);
},
applyConditionalRequired: function() {
$(".require-if-active").each(function() {
var el = $(this);
if ($(el.data("require-pair")).is(":checked")) {
el.prop("required", true);
} else {
el.prop("required", false);
}
});
}
};
FormStuff.init();
</script>
Try this:
$("#choice-form").change(function() {
// If checkbox checked
if ( $('#choice-form').is(':checked') ) {
// Set new form action
$('#form-horizontal').attr('action', 'reservation?action=listRooms');
// Reveal additional options
$('.reveal-if-active').show(); // or call .css() with appropriate options
}
});
Ok, let's say you want to add the id(you can use name as well) and value to the action parameter from the form...
$(document).on('click','.checkboxClass',function(){
var id = $(this).attr('id');
var val = $(this).val();
var selectedVal = '&'+id+'='+val;
var methodUrl = $('form.form-horizontal').attr('action');
if($(this).is(':checked')){
methodUrl+= selectedVal;
}
else{
methodUrl = methodUrl.replace(selectedVal,'');
}
$('form.form-horizontal').attr({'action':methodUrl});
});
Now let's say you have a checkbox with the id="myId" and value="myValue", if you check it, the action parameter will become action="reservation?action=listRooms&myId=myValue"
Is this what you asked for?

print out div in JavaScript if return false

index.php
<body align="center">
<form action="index2.php" method="post" onsubmit="return ValidateEmail()">
<div class="container">
<h1> TEST </h1>
<br>
<label>LOG IN WITH FACEBOOK</label>
<br>
<br>
<label>CHANGE FACEBOOK ACCOUNT</label>
<br>
<br>
<label><input id="Username" type="text" placeholder="name" name="name" maxlength="30"/></label>
<br>
<br>
<label><input id="Useremail" type="text" placeholder="email" name="email"/></label>
<br>
<br>
<label>
<select name="gender">
<option value="male">male</option>
<option value="female">female</option>
</select>
</label>
<br>
<br>
<input type="submit" name="submit" value="Sign Up"/>
</form><!--end of form -->
</body>
JavaScript
<script type="text/javascript">
function IsValidEmail(email) {
var expr = /^([\w-\.]+)#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([\w-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$/;
return expr.test(email);
};
function ValidateEmail() {
var email = document.getElementById("Useremail").value;
if (!IsValidEmail(email)) {
// alert("Invalid email address.");
return false;
!-- print out div that show this alert text-->
}
else {
return true;
!-- else return true dont submit the post-->
}
}
</script>
my intention is when the user dont enter or enter wrong email , it will pop a text or a box in html div and telling them they didt entering the right email , how i going to make javasctrip print out a div your email is invalid ?? if return true submit post else not posted. and i dont wanted to use jquery. thank you
Add A Div for pop text like this
<div id="emailMessage"></div>
Then replace your JavaScript code with this
function IsValidEmail(email) {
var expr = /^([\w-\.]+)#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([\w-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$/;
return expr.test(email);
};
function ValidateEmail() {
var email = document.getElementById("Useremail").value;
if (!IsValidEmail(email)) {
document.getElementById("emailMessage").innerHTML = "Invalid email address.";
//alert("Invalid email address.");
return false;
} else {
document.getElementById("emailMessage").innerHTML = "";
return true;
}
}
You must create an error message in <div> with the attribute hidden.
<div id="errorMessage" hidden>
Error message here...
</div>
The hidden attribute makes the element to be hidden.
If the user enters invalid email, you can set the hidden of that div error message to false.
document.getElementById("errorMessage").hidden=false;
Place that code after/before the return false; of your javascript.
An easier alternative would be to use the HTML5 validation of the email input as suggested in this SO-thread: HTML5 Email Validation.
Just use input type email and the validation will be handled by the browser:
<form>
<input type="email" placeholder="Enter your email">
<input type="submit" value="Submit">
</form>
You can reffer the foolowing sample code
used "" to dispaly the error message.
<!DOCTYPE html>
<html>
<body>
<script type="text/javascript">
function IsValidEmail(email) {
var expr = /^([\w-\.]+)#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([\w-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$/;
return expr.test(email);
}
function myFunction() {
var email = document.getElementById("Useremail").value;
if (!IsValidEmail(email)) {
document.getElementById("errorMsg").innerHTML = "Invalid email address.";
window.stop();
return false;
<!-- print out div that show this alert text-->
}
else {
document.getElementById("errorMsg").innerHTML = "";
return true;
<!-- else return true dont submit the post-->
}
}
</script>
<form method="post" action="index2.php" onsubmit="return myFunction()" >
<div class="container">
<h1> AUG SWIFT TEST </h1>
<br>
<label>LOG IN WITH FACEBOOK</label>
<br>
<br>
<label>CHANGE FACEBOOK ACCOUNT</label>
<br>
<br>
<label><input id="Username" type="text" placeholder="name" name="name" maxlength="30"/></label>
<br>
<br>
<label><input id="Useremail" type="text" placeholder="email" name="email"/></label><div id="errorMsg"></div>
<br>
<br>
<label>
<select name="gender">
<option value="male">male</option>
<option value="female">female</option>
</select>
</label>
<br>
<br>
<input type="submit" onClick="myFunction()" name="submit" value="Sign Up"/>
</form><!--end of form -->
</body>
</html>

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