I have a basic form with some input fields and a dropdown(select field).
Almost all fields have a form of validation. When a field has an error, an error message with the CSS class 'errorText' is displayed next to the field.
By default, my submit button is 'disabled'. I want to remove the 'disabled' attribute from my submit button once all tags with 'errorText' CSS classes are hidden/removed.
my current script just hides all tags with 'errorText' when an error occurs. how do I stop it from doing that and how can I enable my submit button once all fields have been properly enter/validated? Thanks.
EDIT: SOLVED. CODE UPDATED.
// Field Validations
$('#firstName')
.on('blur', function() {
var $this = $(this);
if ($this.val() == '') {
$('label[for="firstName"]').addClass('errorText');
$('#errorFName').show();
} else {
$('label[for="firstName"]').removeClass('errorText');
$('#errorFName').hide();
}
});
$('#lastName')
.on('blur', function() {
var $this = $(this);
if ($this.val() == '') {
$('label[for="lastName"]').addClass('errorText');
$('#errorLName').show();
} else {
$('label[for="lastName"]').removeClass('errorText');
$('#errorLName').hide();
}
});
$('#state')
.on('blur', function() {
var $this = $(this);
if ($('#state').val() == "") {
$('label[for="state"]').addClass('errorText');
$('#errorState').show();
} else {
$('label[for="state"]').removeClass('errorText');
$('#errorState').hide();
}
});
// Submit Button validation
$('input, select').on('keyup, blur', function() {
if ($('.errorText:visible').length ||
$('#firstName' || '#lastName' || '#state').val() == '' ) {
$('input[type="submit"]').prop('disabled', true);
} else if ($('#firstName').val() != '' &&
$('#lastName').val() != '' &&
$('#state').val() != '' ) {
$('input[type="submit"]').prop('disabled', false);
}
});
.errorText {
color: #c4161c;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script>
<div>
<label for="firstName" class="required">First Name</label>
</div>
<div>
<input type="text" name="firstName" id="firstName" />
</div>
<div class="errorText" id="errorFName" style="display:none;">Please enter a First Name</div>
<br />
<div>
<label for="lastName" class="required">Last Name</label>
</div>
<div>
<input type="text" name="lastName" id="lastName" />
</div>
<div class="errorText" id="errorLName" style="display:none;">Please enter a Last Name</div>
<br />
<div>
<label for="state" class="required">State</label>
</div>
<div>
<select name="state" id="state">
<option value="">Select State</option>
<option value="alabama">Alabama</option>
<option value="alaska">Alaska</option>
<option value="arizona">Arizona</option>
<option value="arkansas">Arkansas</option>
<option value="california">California</option>
<option value="etc">etc..</option>
</select>
</div>
<div class="errorText" id="errorState" style="display:none;">Please select a State</div>
<br />
<input type="submit" class="LargeButton" value="Submit Referral" disabled />
If it helps, check this update using data-attribute. We group the label,input,error in a div and handle error message. Also simplified the check valid on input and select element but can be modified.
html
<div>
<label for="firstName" class="required">First Name</label>
<input type="text" name="firstName" id="firstName" />
<span class="errorText" style="display:none;">Please enter a First Name</span>
</div>
<br />
<div>
<label for="lastName" class="required">Last Name</label>
<input type="text" name="lastName" id="lastName" />
<span class="errorText" style="display:none;">Please enter a Last Name</span>
</div>
<br />
<div>
<label for="state" class="required">State</label>
<select name="state" id="state" data-valid="">
<option value="">Select State</option>
<option value="alabama">Alabama</option>
<option value="alaska">Alaska</option>
<option value="arizona">Arizona</option>
<option value="arkansas">Arkansas</option>
<option value="california">California</option>
<option value="etc">etc..</option>
</select>
<span class="errorText" style="display:none;">Please select a State</span>
</div>
<br />
<input type="submit" id="submit" class="LargeButton" value="Submit Referral" disabled />
script
$(function() {
$('input,select')
.on('blur', function() {
var $this = $(this);
if ($this.val() == '') {
$this.data("valid", 'false');
//find the immediate span with errorText and show it
$this.next("span.errorText").show();
} else {
$this.data("valid", 'true');
$this.next("span.errorText").hide();
}
checkInputs();
});
});
function checkInputs() {
//find all the input and select items where the data attribute valid is present and make an array
var array = $('input,select').map(function() {
return $(this).data("valid");
}).get();
//if there are not empty or false indicating invalid value set submit property to true
if (array.indexOf("") == -1 && array.indexOf("false") == -1) {
$("#submit").prop("disabled", false);
} else {
$("#submit").prop("disabled", true);
}
}
css
.errorText {
color: #c4161c;
display: block;
}
Related
I have few fields on this code snippet. Here I have radio button If Field_One is checked show mentioned input field (country select, first name, last name, mobile, email, trans id) same like if Field_Two is checked show mentioned field (reference no, id no and trans id)
Here Trans ID. First Name, Last Name is mandotory for both radio button and its a required field. But I have added few required field without last name.
And Field_Two radio field will show field like reference id and id no. I want if only one field is required field and if only one field is filled up then its ok from both reference id and id no.
But My code is not working properly See the below snippet
One thing if First Country is Africa then show another Dropdown box with Country2 but its also required when Africa is selected but Africa not selected its not required.
$(document).ready(function () {
function make_required_inputs(el) {
let value = el.val();
let div = $('div.' + value);
$('input[required]').removeAttr('required');
div.find('input.required').attr('required', true);
$('input[name="trxid"]').attr('required', true);
}
function validation() {
let valid = true;
$.each($('input[required]'), function () {
if ($(this).val() == '') valid = false;
});
if (valid) {
jQuery('#button1').attr('disabled', false);
} else {
jQuery('#button1').attr('disabled', true);
}
}
$('input[type="radio"]').click(function () {
if ($(this).attr("value") == "Field_One") {
$(".Field_One").show();
$(".Field_Two").hide();
$("#country").show();
}
if ($(this).attr("value") == "Field_Two") {
$(".Field_Two").show();
$(".Field_One").hide();
$("#country").hide();
}
validation();
});
let checked = $('input[name="myfield"]:checked');
let value_checked = checked.attr("value");
if (value_checked == "Field_One") {
$(".Field_One").show();
$(".Field_Two").hide();
}else if (value_checked == "Field_Two") {
$(".Field_Two").show();
$(".Field_One").hide();
}
$('input[type="radio"]')
make_required_inputs($('input[name="myfield"]:checked'));
$('input[name="myfield"]').on('change', function () {
make_required_inputs($(this));
validation();
});
$('input').keyup(function (e) {
validation();
});
jQuery("#country").change(function(){
jQuery(this).find("option:selected").each(function(){
var optionValue = jQuery(this).attr("value");
if(optionValue=='za'){
jQuery("#country2").show();
} else{
jQuery("#country2").hide();
}
});
}).change();
jQuery("#country2").hide();
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="radio" name="myfield" value="Field_One" checked="true" /> Field_One
<input type="radio" name="myfield" value="Field_Two" /> Field_Two
<br><br>
<select name="country" class="required" id="country">
<option>Select</option>
<option value="us">US</option>
<option value="uk">UK</option>
<option value="za">Africa</option>
</select>
<br><br>
<select name="country2" class="required" id="country2">
<option>Select</option>
<option value="eg">Egypt</option>
<option value="ng">Nigeria</option>
<option value="gh">Ghana</option>
<option value="za">South Africa</option>
</select>
<br><br>
<input type="text" name="first_name" class="required" placeholder="First Name" />
<br><br>
<input type="text" name="last_name" placeholder="Last Name"/>
<br><br>
<div class="Field_One">
<input type="text" name="mobile_no" placeholder="Mobile no"/>
<br><br>
<input type="text" class="required" name="email" placeholder="Email"/>
</div>
<br>
<div class="Field_Two">
<input type="text" name="reference_no" class="required" placeholder="Reference no" /><br><br>
<input type="text" name="id_no" class="required" placeholder="ID no" />
</div><br>
<input type="text" name="trxid" class="required" placeholder="Trans ID" />
<input type="submit" id="button1" value="Submit" disabled/>
Update:
$(document).ready(function () {
function validation() {
let valid = true;
$.each($('input[required]:not([name="reference_no"],[name="id_no"]),select[required]'), function () {
if ($(this).val() == '') valid = false;
});
let one = 0;
if ($('input[one="true"][required]').length == 0) {
one = 1;
} else {
one = 0;
$.each($('input[one="true"][required]'), function () {
if ($(this).val() !== '') one++;
});
}
if (valid && one > 0) {
jQuery('#button1').prop('disabled', false);
} else {
jQuery('#button1').prop('disabled', true);
}
}
function required(value) {
$('input.required,select.required').prop('required', true);
if (value == "Field_One") {
$(".Field_One").show();
$(".Field_Two").hide().find('input,select').prop('required', false);
$("#country").show().addClass('required').prop('required', true);
}
if (value == "Field_Two") {
$(".Field_Two").show();
$(".Field_One").hide().find('input,select').prop('required', false);
$("#country").hide().removeClass('required').prop('required', false);
jQuery("#country2").hide().removeClass('required').prop('required', false);
}
validation();
}
$('input[type="radio"]').click(function () {
required($(this).val());
});
let value_checked = $('input[name="myfield"]:checked').attr("value");
required(value_checked);
$('select,input').on('change keyup', function () {
validation();
});
jQuery("#country").change(function () {
var optionValue = jQuery(this).find("option:selected").attr("value");
if (optionValue == 'za') {
jQuery("#country2").show().addClass('required').prop('required', true);;
} else {
jQuery("#country2").hide().removeClass('required').prop('required', false);;
}
validation();
}).change();
jQuery("#country2").hide().removeClass('required').prop('required', false);
});
let valid2 = true;
$.each($('#domain_name,select[required]'), function () { if ($(this).val() == '') valid2 = false; }); if (valid2) { jQuery('#domsBtn').prop('disabled', false); } else { jQuery('#domsBtn').prop('disabled', true); }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="radio" name="myfield" value="Field_One" checked="true" /> Field_One
<input type="radio" name="myfield" value="Field_Two" /> Field_Two
<br><br>
<select name="country" class="required" id="country">
<option value="">Select</option>
<option value="us">US</option>
<option value="uk">UK</option>
<option value="za">Africa</option>
</select>
<select name="country2" class="required" id="country2">
<option value="">Select</option>
<option value="eg">Egypt</option>
<option value="ng">Nigeria</option>
<option value="gh">Ghana</option>
<option value="za">South Africa</option>
</select>
<br><br>
<input type="text" name="first_name" class="required" placeholder="First Name" />
<br><br>
<input type="submit" id="firstCheck" value="First Name Check" disabled />
<br><br>
<input type="text" name="last_name" placeholder="Last Name" />
<br><br>
<div class="Field_One">
<input type="text" name="mobile_no" placeholder="Mobile no" />
<br><br>
<input type="text" class="required" name="email" placeholder="Email" />
</div>
<br>
<div class="Field_Two">
<input type="text" name="reference_no" one="true" class="required" placeholder="Reference no" /><br><br>
<input type="text" name="id_no" one="true" class="required" placeholder="ID no" />
</div><br>
<input type="text" name="trxid" class="required" placeholder="Trans ID" />
<input type="submit" id="button1" value="Submit" disabled />
I'm creating a form and I made a validation so it has a field is required text popping up when you click the submit button.
It works pretty well but, it has 1 problem. When it pops up, and I select an option from the select tag, the field is required text doesn't hide automatically, but when it's an input text and I type something in it, the text hides automatically.
$('#name').on('change', function() {
if (this.value != "") {
this.removeAttribute("required");
this.required = false;
}
});
function Validate(_id) {
$("#form_validation").validate({
rules: rules,
highlight: function(input) {
$(input).parents('.form-line').addClass('error');
},
unhighlight: function(input) {
$(input).parents('.form-line').removeClass('error');
},
errorPlacement: function(error, element) {
$(element).parents('.form-group').append(error);
}
});
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="form-group form-float">
<div class="form-line">
<select class="form-control show-tick" name="name" id="name" required>
<option value="" disabled selected hidden="">-- Please select --</option>
<option value="1">Option 1</option>
<option value="2">Option 2</option>
<option value="3">Option 3</option>
</select>
</div>
</div>
<div class="form-group form-float" align="center">
<input type="submit" name="insert" class="btn btn-lg large" id="data">
</div>
Have you tried to put the attribute novalidate on the SELECT tag?
Example:
<select class="form-control show-tick" name="name" id="name" required novalidate>
Make sure that you are typing the right selector in this snippet:
$('#elemschool').on('change', function() {
if (this.value != "") {
this.removeAttribute("required");
this.required = false;
}
});
change elemschool to name as the id in the select
<select class="form-control show-tick" name="name" id="name" required>
is equal to name
so basically it will be like below:
$('#name').on('change', function() { // here is the change
if (this.value != "") {
this.removeAttribute("required");
this.required = false;
}
});
I have a textarea element that is not displayed. If the user selects "Other" option in the select element, the textarea should show, but it is not showing with the below code.
The following is my select element :
<select class="form-control" name="feed" id="feed" value="" style="width:540px">
<option selected="selected" disabled="true">Please select</option>
<!-- <option></option> -->
<option value="Excellent" id="Excellent"> All text is excellent</option>
<option value="Other" id="Other" onclick="showHide(this)"
>Other feedback (free text)</option
>
</select>
The following is my textarea element :
<div class="form-group">
<label for="fb_text"></label>
<textarea
class="form-control"
name="fb_text"
id="fb_text"
rows="5"
placeholder="Describe yourself here..."
value=""
style="width:540px;display:none"
></textarea>
</div>
The following is my JS :
function showHide(elm) {
var Fbtext = document.getElementById("fb_text");
if (document.getElementById("feed").value == "Other") {
Fbtext.classList.remove("hide");
}
}
You can pass value from select using onchangeevent to your function and check if that value is equals to Others if yes display textarea else hide it. Working example :
function showHide(elm) {
if (elm == "Other") {
//display textbox
document.getElementById('fb_text').style.display = "block";
} else {
//hide textbox
document.getElementById('fb_text').style.display = "none";
}
}
<select class="form-control" name="feed" id="feed" value="" onchange="showHide(this.value)" style="width:540px">
<option selected="selected" disabled="true">Please select</option>
<!-- <option></option> -->
<option value="Excellent" id="Excellent"> All text is excellent</option>
<option value="Other" id="Other">Other feedback (free text)</option>
</select>
<div class="form-group">
<label for="fb_text"></label>
<textarea class="form-control" name="fb_text" id="fb_text" rows="5" placeholder="Describe yourself here..." value="" style="width:540px;display:none"></textarea>
</div>
Add change event to the select element, see if the selected option is 'Other', hide the text area else show.
const textareaEle = document.querySelector('textarea');
document.querySelector('select').addEventListener('change', function() {
textareaEle.style.display = (this.value == 'Other') ? 'block' : 'none';
});
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" rel="stylesheet"/>
<select class="form-control" name="feed" id="feed" value="" style="width:540px">
<option selected="selected" disabled="true">Please select</option>
<!-- <option></option> -->
<option value="Excellent" id="Excellent"> All text is excellent</option>
<option value="Other" id="Other">Other feedback (free text)</option>
</select>
<div class="form-group">
<label for="fb_text"></label>
<textarea class="form-control hide" name="fb_text" id="fb_text" rows="5" placeholder="Describe yourself here..." value="" style="width:540px;"></textarea>
</div>
I have not checked but I understand in your code you try to remove a class (hide) that you have not assigned, because you hide the textarea with the attribute style
Please try this example, I understand in your example you use bootstrap, for demonstration I have added hide
const feed = document.querySelector('#feed');
const fbtext = document.querySelector('#fb_text');
feed.addEventListener('change', handleChange);
function handleChange(event) {
const value = event.target.value;
if (value === 'Other') {
fbtext.classList.remove('hide');
return false;
}
fbtext.classList.add('hide');
}
.hide {
display: none;
}
<select
class="form-control"
name="feed"
id="feed"
value=""
style="width:540px"
>
<option selected="selected" disabled="true">Please select</option>
<option value="Excellent" id="Excellent"> Excellent</option>
<option value="Other" id="Other">Other</option>
</select>
<div class="form-group">
<label for="fb_text"></label>
<textarea
class="form-control hide"
name="fb_text"
id="fb_text"
rows="5"
placeholder="Describe yourself here..."
></textarea>
</div>
I send form data using Jquery's $("form").serialize() method. I display the serialized data as alert($("form").serialize()); and found some repeated messages.
What could be the problem there?
The logged message is shown in the attached image.
There are repeated data (underlined). The first one is fine stories=3&bedrooms=2&bathrooms=2 for three SELECT elements. Then there is another repeated message with bedrooms=Bedrooms&bathroom=Bathrooms, then my PHP code at server caught the second one and the value is never changed.
stories=3&bedrooms=2&bathrooms
are three SELECT elements and their default options for bedrooms and bathrooms are Bedrooms and Bathrooms. Because of the repeated data, no matter I change other options at bedrooms and bathrooms, the value sent to server is never changed.
What could be the problem and how to solve?
Thanks
EDIT:
My HTML code is long. I am just beginner for Webapplications, not sure they are in appropriate way, anyway they are as follow. There are two steps validations, one at client side in the function function validatelanded( event ) and another one at server function sendtoServer().
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<link rel="stylesheet" href="//code.jquery.com/ui/1.11.4/themes/smoothness/jquery-ui.css">
<script src="//code.jquery.com/jquery-1.10.2.js"></script>
<script src="//code.jquery.com/ui/1.11.4/jquery-ui.js"></script>
<link rel="stylesheet" href="/resources/demos/style.css">
<style type="text/css">
#header { background-color:green; color:white; text-align:center; padding:5px;}
#background {background: url(register_background.png);}
body {
background-color: #cccccc;
}
.star { color: red;}
.button { background-color: #4CAF50; border: none; color: white; padding: 15px 32px; text-align: center; text-decoration: none; display: inline-block; font-size: 16px; margin: 4px 2px; cursor: pointer;
}
.button2:hover { box-shadow: 0 12px 16px 0 rgba(0,0,0,0.24),0 17px 50px 0 rgba(0,0,0,0.19);}
.overflow { height: 200px; }
select[required] + label {
color: #999;
font-family: Arial;
font-size: 17px;
position: relative;
/*left: -230px; the negative of the input width */
}
select[required] + label:after {
content:'*';
color: red;
}
input[required] + label {
color: #999;
font-family: Arial;
font-size: 17px;
position: relative;
/*left: -230px; the negative of the input width */
}
input[required] + label:after {
content:'*';
color: red;
}
input[need] + text{
color: #999;
font-family: Arial;
font-size: 17px;
position: relative;
/*left: -230px; the negative of the input width */
}
</style>
</head>
<body>
<div id="header">
<h1>Please add your landed property to advertise</h1>
</div>
<div id="background">
<form name="advertiseForm" id="advertiseForm" method="post" >
<br /><br />
<div class="form_box">
<div class="input_box ">
<input type="radio" name="purpose" value="Sell" >To sell
<input type="radio" name="purpose" value="Rent" required="required">To rent
<label for="purpose">Please select transaction type</label>
<div id="purpose-error" class="error-box" style="color:#FF0000">
</div>
</div>
<div class="clear"></div>
</div>
<br /><br />
<div class="form_box">
<div class="input_box ">
<input class="type" type="radio" name="type" value="No_building" >No building
<input class="type" type="radio" name="type" value="With_RC">With RC
<input class="type" type="radio" name="type" value="With_BrickNorcal" required="required">With BrickNorcal
<label for="type">Please select building type</label>
<div id="type-error" class="error-box" style="color:#FF0000"></div>
</div>
<div class="clear"></div>
</div>
<br /><br /><br />
<select name="stories" id="stories" required="required"/>
<option value="Stories" >Number of stories</option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
<option value="morethan4">More than 4</option>
<select/>
<label for="stories">Please select for number of stories</label>
<div id="stories-error" class="error-box" style="color:#FF0000"></div>
<br /><br /><br />
<select name="bedrooms" id="bedrooms" required="required"/>
<option value="Bedrooms" >Number of bedrooms</option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
<option value="5">5</option>
<select/>
<label for="numbedrooms">Please select for number of bedrooms</label>
<div id="bedrooms-error" class="error-box" style="color:#FF0000"></div>
<br /><br /><br />
<select name="bathrooms" id="bathrooms" required="required"/>
<option value="Bathrooms" >Number of Bathrooms</option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
<option value="5">5</option>
<select/>
<label for="bathrooms">Please select for number of bathrooms</label>
<div id="bathrooms-error" class="error-box" style="color:#FF0000"></div>
<br /><br /><br />
<select name="divs_states" id="divs_states" required="required"/>
<optgroup label="Divisions">
<option value="Division">Please select one of the following divisions</option>
<option value="jquery">jQuery.js</option>
<option value="jqueryui">ui.jQuery.js</option>
</optgroup>
<optgroup label="States">
<option value="State">Please select one of the following states</option>
<option value="somefile">Some unknown file</option>
<option value="someotherfile">Some other file with a very long option text</option>
</optgroup>
<select/>
<label for="divs_states">Please select a region</label>
<div id="divs_states-error" class="error-box" style="color:#FF0000"></div>
<br /><br /><br />
<select name="township" id="township" required="required"/>
<option value="Township" >Township</option>
<option value="saab">Saab</option>
<option value="fiat">Fiat</option>
<option value="audi">Audi</option>
<select/>
<label for="township">Please select a nearest township</label>
<div id="township-error" class="error-box" style="color:#FF0000"></div>
<br /><br /><br />
<div class="form_box">
<div class="input_box">
<input maxlength="100" type="price" name="price" id="price" required="required" />
<label for="price">Price</label>
<div id="price-error" class="error-box" style="color:#FF0000"></div>
</div>
<div class="clear"></div>
</div>
<br /><br />
<div class="form_box">
<div class="input_box">
<input maxlength="100" type="length" name="length" id="length" required="required" />
<label for="length">Length in feet</label>
<input maxlength="100" type="width" name="width" id="width" required="required" />
<label for="width">Width in feet</label>
<br />
<div id="length-error" class="error-box" style="color:#FF0000"></div>
<div id="width-error" class="error-box" style="color:#FF0000"></div>
</div>
<div class="clear"></div>
</div>
<br />
<input type="radio" name="havetelephone" value="yes" checked>Yes
<input type="radio" name="havetelephone" value="no" need="need">No
<text for="havetelephone">Landline telephone installed at home?</text>
<br /><br />
<input type="radio" name="haveaircon" value="yes">Yes
<input type="radio" name="haveaircon" value="no" required="required">No
<label for="haveaircon">Aircon installed?</label>
<div id="haveaircon-error" class="error-box" style="color:#FF0000"></div>
<br /><br /><br />
<select name="possession" required="required"/>
<option value="Possession" >Possession</option>
<option value="saab">Saab</option>
<option value="fiat">Fiat</option>
<option value="audi">Audi</option>
<select/>
<label for="possession">Please select a possession type</label>
<div id="possession-error" class="error-box" style="color:#FF0000"></div>
<br /><br /><br />
<input maxlength="100" type="text" name="date" id="date" required="required" />
<label for="date">Please specify an available date for start use</label>
<div id="date-error" class="error-box" style="color:#FF0000"></div>
<br /><br /><br />
<textarea rows="20" cols="70" name="textarea" id="textarea" placeholder="Please enter additional information here..."></textarea>
<div id="textarea-error" class="error-box" style="color:#FF0000"></div>
<br /><br />
<div style="color:#0000FF">
<h3>Contact address</h3>
</div>
<br />
<input type="radio" name="agentowner" value="Agent" >Agent
<input type="radio" name="agentowner" value="Owner" required="required">Owner
<label for="agentowner">Please specify</label>
<div id="agentowner-error" class="error-box" style="color:#FF0000"></div>
<br /><br />
<div class="form_box">
<div class="input_box ">
<input maxlength="60" type="text" name="name" id="name" required="required" />
<label for="name">Name</label>
<div id="name-error" class="error-box" style="color:#FF0000"></div>
</div>
<div class="clear"></div>
</div>
<br /><br />
<div class="form_box">
<div class="input_box ">
<input maxlength="60" type="text" name="phone" id="phone" required="required" />
<label for="phone">Phone</label>
<div id="phone-error" class="error-box" style="color:#FF0000"></div>
</div>
<div class="clear"></div>
</div>
<br /><br />
<div class="form_box">
<div class="input_box">
<input maxlength="64" type="text" name="email" id="email" required="required" />
<label for="email">Email</label>
<div id="email-error" class="error-box" style="color:#FF0000"></div>
</div>
<div class="clear"></div>
</div>
<br /><br />
<textarea rows="10" cols="50" name="address" id="address" placeholder="Please key in full address if you are ok..."></textarea>
<!-- Check on the page itself first -->
<br /><br /><br />
<div style="text-align:center">
<input class="button button2" id="submitbutton" type="button" value="Submit" />
</div>
</form>
</div>
</body>
<script>
$("#textarea")
.focus(function() {
if ($("#textarea").val() == null) return;
if ($("#textarea").val() == "Please enter additional information here...")
$("#textarea").val('');
})
.blur(function() {
if ($("#textarea").val() == null) return;
if ($("#textarea").val() == '')
$("#textarea").val('Please enter additional information here...');
});
$("#address")
.focus(function() {
if ($("#address").val() == null) return;
if ($("#address").val() == "Please key in full address if you are ok...")
$("#address").val('');
})
.blur(function() {
if ($("#address").val() == null) return;
if ($("#address").val() == '')
$("#address").val('Please key in full address if you are ok...');
});
$(function() {
$( "#date" ).datepicker();
});
function trimAll( str ) {
return str.replace( /^\s+|\s+$/g, '' );
}
function sendtoServer() {
alert($("form").serialize());
$.ajax({
url: "advertisementdatavalidationatserver.php",
type: "POST",
data: $("form").serialize(),
success: function(ret){
alert(ret);
if(ret.error == true){
if(ret.message.indexOf("Purposeerror")>=0){
$('#purpose-error').css('display', 'block');
$('#purpose-error').html('Please enter to rent or to sell');
}else{
$('#purpose-error').html('');
}
if(ret.message.indexOf("Typeerror")>=0){
$('#type-error').css('display', 'block');
$('#type-error').html('Please enter your building type');
}else{
$('#type-error').html('');
}
if(ret.message.indexOf("Storieserror")>=0){
$('#stories-error').css('display', 'block');
$('#stories-error').html('Please enter number of stories at your building');
}else{
$('#stories-error').html('');
}
if(ret.message.indexOf("Bedroomserror")>=0){
$('#bedrooms-error').css('display', 'block');
$('#bedrooms-error').html('Please enter number of bedrooms at your building');
}else{
$('#bedrooms-error').html('');
}
if(ret.message.indexOf("Bathroomserror")>=0){
$('#bathrooms-error').css('display', 'block');
$('#bathrooms-error').html('Please enter number of bathrooms at your building');
}else{
$('#bathrooms-error').html('');
}
if(ret.message.indexOf("Divisionerror")>=0){
$('#divs_states-error').css('display', 'block');
$('#divs_states-error').html('Please select a Division or a State');
}else{
$('#divs_states-error').html('');
}
if(ret.message.indexOf("Townshiperror")>=0){
$('#township-error').css('display', 'block');
$('#township-error').html('Please select a Township');
}else{
$('#township-error').html('');
}
if(ret.message.indexOf("Priceerror")>=0){
$('#price-error').css('display', 'block');
$('#price-error').html('Please include the price');
}else{
$('#price-error').html('');
}
if(ret.message.indexOf("Priceinvalid")>=0){
$('#price-error').css('display', 'block');
$('#price-error').html('Price accepts only neumerical digits');
}else{
$('#price-error').html('');
}
}else{
$('#purpose-error').html('');
$('#type-error').html('');
$('#stories-error').html('');
$('#bedrooms-error').html('');
$('#bathrooms-error').html('');
$('#divs_states-error').html('');
$('#township-error').html('');
$('#price-error').html('');
}
},
error: function(){
// the AJAX request failed as in timed out / bad url etc.
}
});
}
$( "#submitbutton" ).on( "click", validatelanded );
function validatelanded( event ){
if (!$("input[name='purpose']:checked").val()) {
$('#purpose-error').css('display', 'block');
$('#purpose-error').html('Please select to Sell or to Rent');
return false;
}else{
$('#purpose-error').html('');
}
if (!$("input[name='type']:checked").val()) {
$('#type-error').css('display', 'block');
$('#type-error').html('Please select one of the Building types');
return false;
}else{
$('#type-error').html('');
}
if($("input[name='type']:checked").val() == "With_RC" || $("input[name='type']:checked").val() == "With_BrickNorcal"){
if($( "#stories" ).val() == "Stories"){
$('#stories-error').css('display', 'block');
$('#stories-error').html('Please select number of stories at the building');
return false;
}else{
$('#stories-error').html('');
}
if($( "#bedrooms" ).val() == "Bedrooms"){
$('#bedrooms-error').css('display', 'block');
$('#bedrooms-error').html('Please select number of bedrooms at the building');
return false;
}else{
$('#bedrooms-error').html('');
}
if($( "#bathrooms" ).val() == "Bathrooms"){
$('#bathrooms-error').css('display', 'block');
$('#bathrooms-error').html('Please select number of bathrooms at the building');
return false;
}else{
$('#bathrooms-error').html('');
}
}
if($( "#divs_states" ).val() == "Division" || $( "#divs_states" ).val() == "State"){
$('#divs_states-error').css('display', 'block');
$('#divs_states-error').html('Please select a Division or a State');
return false;
}else{
$('#divs_states-error').html('');
}
if($( "#township" ).val() == "Township" ){
$('#township-error').css('display', 'block');
$('#township-error').html('Please select a township');
return false;
}else{
$('#township-error').html('');
}
var price = $('#price').val();
if ($.trim(price) == '' ) {
$('#price-error').css('display', 'block');
$('#price-error').html('Please include price');
return false;
}else if(!price.match(/^\d+$/)){
$('#price-error').css('display', 'block');
$('#price-error').html('Price can include only numerical digits');
return false;
}else{
$('#price-error').html('');
}
var length = $('#length').val();
if ($.trim(length) == '' ) {
$('#length-error').css('display', 'block');
$('#length-error').html('Please include length of the land');
return false;
}else if(!length.match(/^\d+$/)){
$('#length-error').css('display', 'block');
$('#length-error').html('Please include length in correct format');
return false;
}else{
$('#length-error').html('');
}
var width = $('#width').val();
if ($.trim(width) == '' ) {
$('#width-error').css('display', 'block');
$('#width-error').html('Please include width of the land');
return false;
}else if(!width.match(/^\d+$/)){
$('#width-error').css('display', 'block');
$('#width-error').html('Please include width in correct format');
return false;
}else{
$('#width-error').html('');
}
if (!$("input[name='haveaircon']:checked").val()) {
$('#haveaircon-error').css('display', 'block');
$('#haveaircon-error').html('Please select for the aircon');
return false;
}else{
$('#haveaircon-error').html('');
}
if($( "#possession" ).val() == "Possession"){
$('#possession-error').css('display', 'block');
$('#possession-error').html('Please select possession type');
return false;
}else{
$('#possession-error').html('');
}
if ($.trim($('#date').val()) == '' ) {
$('#date-error').css('display', 'block');
$('#date-error').html('Please include available date for start use');
return false;
}else{
$('#date-error').html('');
}
if ($('#textarea').val() == "" || $('#textarea').val() =="Please enter additional information here...")
{
$('#textarea-error').css('display', 'block');
$('#textarea-error').html('Please enter additional information in the above text area...');
return false;
}else{
$('#textarea-error').html('');
}
if (!$("input[name='agentowner']:checked").val()) {
$('#agentowner-error').css('display', 'block');
$('#agentowner-error').html('Please select Agent or Owner');
return false;
}else{
$('#agentowner-error').html('');
}
var name = $('#name').val();
if( $.trim(name) == '' ){
$('#name-error').css('display', 'block');
$('#name-error').html('Please include name of the person who submit this advertisement.');
return false;
}else{
$('#name-error').html('');
}
var phone= $('#phone').val();
if ($.trim(phone) == '') {
$('#phone-error').css('display', 'block');
$('#phone-error').html('Please include phone number to contact.');
return false;
} else if(phone.length < 6){
$('#phone-error').css('display', 'block');
$('#phone-error').html('Please include valid phone number to contact.');
return false;
}else if (!phone.match(/^[0-9]+$/)){
$('#phone-error').css('display', 'block');
$('#phone-error').html('Please include valid phone number to contact.');
return false;
}else{
$('#phone-error').html('');
}
var email= $('#email').val();
if ($.trim(email) == '') {
$('#email-error').css('display', 'block');
$('#email-error').html('Please include email number to contact.');
return false;
}else if (!email.match(/^[-a-z0-9~!$%^&*_=+}{\'?]+(\.[-a-z0-9~!$%^&*_=+}{\'?]+)*#([a-z0-9_][-a-z0-9_]*(\.[-a-z0-9_]+)*\.(aero|arpa|biz|com|coop|edu|gov|info|int|mil|museum|name|net|org|pro|travel|mobi|[a-z][a-z])|([0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}))(:[0-9]{1,5})?$/i)) {
$('#email-error').css('display', 'block');
$('#email-error').html('Please include valid email number to contact.');
return false;
}else{
$('#email-error').html('');
}
sendtoServer();
}
</script>
</html>
When I work with multiple forms I give each opening <form> tag a unique id and serialize data on that specific id. Your form in your edit has the 'advertiseForm' id, not 'form'. Don't forget the # character when writing ids in js.
Your js should look like this: $("#advertiseForm").serialize(), this will serialize the form with the id 'advertiseForm'. The other form must also have a unique id or class name in order to serialize it properly.
I am quite new to javascript and am trying to make a validation form that validates once you click out of the input field. I have been trying out many different ways to add on blur to a current validating form which I have created.
How could I add on blur to my validation form? Thanks :)
function addFormValidation(theForm) {
if (theForm === null || theForm.tagName.toUpperCase() !== 'FORM') {
throw new Error("expected first parameter to addFormValidation to be a FORM.");
}
theForm.noValidate = true;
theForm.addEventListener('submit', function(evt) {
var isError = false;
var elements = this.elements;
for (var i = 0; i < elements.length; i += 1) {
if (! isFieldValid(elements[i])) {
isError = true;
}
}
if (isError) {
evt.preventDefault();
}
});
function isFieldValid(field) {
var errorMessage = "";
if (! needsToBeValidated(field)) {
return true;
}
if (field.id.length === 0 || field.name.length === 0) {
console.error("error: ", field);
throw new Error("found a field that is missing an id and/or name attribute. name should be there. id is required for determining the field's error message element.");
}
field.classList.remove('invalid');
var errorSpan = document.querySelector('#' + field.id + '-error');
if (errorSpan === null) {
console.error("error: ", field);
throw new Error("could not find the '#" + field.id + "-error' element. It's needed for error messages if #" + field.id + " is ever invalid.");
}
errorSpan.classList.remove('danger');
errorSpan.innerHTML = "";
if (field.minLength > 0 && field.value.length < field.minLength) {
errorMessage = "Must be " + field.minLength + " or more characters long.";
}
if (field.type === "email" && !isEmail(field.value)) {
errorMessage = "This should be a valid email address.";
}
if (field.required && field.value.trim() === "") {
errorMessage = "This field is required.";
}
if (errorMessage !== "") {
field.classList.add('invalid');
errorSpan.classList.add('danger');
errorSpan.innerHTML = errorMessage;
return false;
}
return true;
}
function needsToBeValidated(field) {
return ['submit', 'reset', 'button', 'hidden', 'fieldset'].indexOf(field.type) === -1;
}
function isEmail(input) {
return input.match(/^([a-z0-9_.\-+]+)#([\da-z.\-]+)\.([a-z\.]{2,})$/);
}
}
HTML
<div class="content">
<form id="contact-form" method="POST" action="success.html">
<div class="form-group">
<label for="firstname">First Name</label>
<input id="firstname" type="text" name="firstname" value="" onblur="addFormValidation('firstname');"/>
<span id="firstname-error"></span>
</div>
<div class="form-group">
<label for="lastname">Last Name</label>
<input id="lastname" type="text" name="lastname" onblur="addFormValidation('lastname');">
<span id= "lastname-error" ></span>
</div>
<div class="form-group">
<label for="email">Email Address</label>
<input id="email" type="email" name="email" required>
<span id="email-error"></span>
</div>
<div class="form-group">
<label for="flight">Flight</label>
<select name="flight" id="flight" required>
<option value="">Please select a flight</option>
<option value="1">Fixed Wing</option>
<option value="2">Helicopter</option>
<option value="3">Glider</option>
</select>
<span id="flight-error"></span>
</div>
<div class="form-group">
<label for="date">Date</label>
<input id="date" type="date" name="date" required>
<span id="date-error"></span>
</div>
<div class="form-group">
<label for="time">Time</label>
<input id="time" type="time" name="time" required>
<span id="time-error"></span>
</div>
<div class="form-group">
<label for="duration">Duration</label>
<select name="duration" id="duration" required>
<option value="">Please select your desired duration</option>
<option value="1">1 Hour</option>
<option value="2">2 Hours</option>
<option value="3">3 Hours</option>
<option value="4">4 Hours</option>
<option value="5">5 Hours</option>
</select>
<span id="duration-error"></span>
</div>
<div class="form-group">
<button type="submit">Submit</button>
</div>
</form>
</div>
<script>
document.addEventListener('DOMContentLoaded', function() {
addFormValidation(document.querySelector('#contact-form'));
});
</script>
http://jsfiddle.net/dLz5w2tz/
I always recommend not using element attributes (onblur) for javascript event execution; instead you can add the listener to your javascript code.
I've done the following to your code:
Remove "onblur" attributes
Add code in your JS to listen to blur events on the entire form (all elements).
JS snipped
theForm.addEventListener('blur', function(evt) {
console.log(evt);
}, true);
Updated JS Fiddle: http://jsfiddle.net/dLz5w2tz/1/
Note:
addEventListner takes 3 parameters -
1. "event"
2. function to execute
3. boolean - should it bubble/propagate the event upwards.
So basically, in this code, the event takes place on the form element (input) and bubbles up to the form itself. You can verify this by looking at the event variable (evt).