Jquery's form serialization sends repeated information - javascript

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.

Related

How do I add checks to make the code to display 'Password too short' and 'Height is not a number?'

I have to add checks to the checkSubmit() function so that it will give the following response
Passwords do not match
Passwords is too short(minimum 4 characters)
Height is not a number
I have managed the first one however I have no idea where to start with the other two. I'll post all the code just to be safe in case I missed something.
<!DOCTYPE HTML>
<html lang="en">
<head>
<title>Form Validation</title>
<meta charset="utf-8">
<link rel="stylesheet" type="text/css" href="styles/styles.css">
<link rel="stylesheet" type="text/css" href="styles/forms.css">
<script type="text/javascript">
window.onload=init;
var form;
function init() {
form = document.getElementById('testform');
form.addEventListener("submit", checkSubmit, false);
form.addEventListener("reset", checkReset, false);
form['colour'].addEventListener("change", checkSubmit, false);
form['name'].focus();
}
String.prototype.trim=function() {
return this.replace(/^\s+1\s+$/g, '');
}
function whichButton(name) {
var buttons=document.getElementsByName(name);
for (var i in buttons) {
if(buttons[i].checked) return buttons[i].value
}
return false;
}
function showOtherColour() {
document.getElementById('othercolour').style.visibility=
form['colour'].value=='other' ? 'visible' : 'hidden';
}
function checkSubmit() {
error = new Array();
//Fill the array with the error value
form['name'].value=form['name'].value.trim();
form['email'].value=form['email'].value.trim();
form['town'].value=form['town'].value.trim();
form['state'].value=form['state'].value.trim();
form['postcode'].value=form['postcode'].value.trim();
form['dob'].value=form['dob'].value.trim();
form['height'].value=form['height'].value.trim();
//Check required fields
if(!form['name'].value)
error.push('Missing Name');
if(!form['email'].value)
error.push('Missing Email Address');
if(!form['password'].value)
error.push('Missing Password');
//Check valid email address
var pattern=/^[a-zA-Z0-9._%-]+#[a-zA-Z0-9.-]+(\.[a-zA-Z]{2,4})$/;
if(!form['email'].value.match(pattern))
error.push('Invalid Email Address');
//Check State
//Check Post Code has 4 digits
var pattern=/^\d{4}$/;
if(!form['postcode'].value.match(pattern))
error.push('Invalid Post Code');
//Check password matches confirmation
//var password = ;
/*
if(!form['passwordConfirm'].value.match(password)){
error.push("Passwords don't match");
}*/
console.log(form['confirm'].value);
console.log(form['password'].value);
if(!form['confirm'].value.match(form['password'].value)){
error.push('Passwords do not match');
}
//Check that one Gender item is selected
if(whichButton('gender')===false)
error.push('Please choose a Gender');
//Check that "Other" field is filled
if (!form['colour'].value ||
(form['colour'].value=='other' && !form['othercolour'].value))
error.push('Colour is not selected');
if(error.length) { // if there are errors
alert(error.join("\n"))
return false;
}
else return true;
//return confirm("This will submit the form"); //Temporary placeholder
}
function checkReset() {
return confirm("This will clear the form data");
}
</script>
<style type="text/css">
body,td,th {
font-size: 0.9em;
}
</style>
</head>
<body>
<div id="body">
<h1>Form Validation</h1>
<form action="http://test.miform.net" method="post" id="testform">
<fieldset>
<label>Name<br><input type="text" name="name" class="wide"></label>
<label>Email Address<br><input type="text" name="email" class="wide"></label>
</fieldset>
<fieldset>
<label>Address<br><input type="text" name="street" class="wide"></label>
<label>Town<br><input type="text" name="town" class="narrow"></label>
<label>State<br><input type="text" name="state" class="narrow"></label>
<label>PostCode<br><input type="text" name="postcode" class="narrow"></label>
</fieldset>
<fieldset>
<label>Password<br><input type="password" name="password" class="medium"></label>
<label>Confirm Password<br><input type="password" name="confirm" class="medium"></label>
</fieldset>
<fieldset>
<label>Date of Birth<br><input type="text" name="dob" class="medium"></label>
<label>Height<br><input type="text" name="height" class="medium"></label>
</fieldset>
<fieldset>
<legend>Gender</legend>
<label><input type="radio" name="gender" value="f">Female</label>
<label><input type="radio" name="gender" value="m">Male</label>
</fieldset>
<fieldset>
<label>Colour
<select name="colour">
<option value="">Select...</option>
<option value="black">Black</option>
<option value="white">White</option>
<option value="red">Red</option>
<option value="green">Green</option>
<option value="blue">Blue</option>
<option value="cyan">Cyan</option>
<option value="magenta">Magenta</option>
<option value="yellow">Yellow</option>
<option value="other">Other</option>
</select>
</label>
<input type="text" id="othercolour">
</fieldset>
<input type="reset" name="reset" value="Clear Form">
<input type="submit" name="send" value="Send Off">
</form>
</div>
</body>
</html>
Do this for the second:
if (form['password'].value.length < 4) {
error.push("Password is too short");
}
And this for the third:
if (isNan(Number(form['height'].value))) {
error.push("Height is not a number");
}

Tabs Widget JQuery not displaying correctly, Correct links already linked

Here is the code in JS Fiddle
or my Github for each file indvidually
My tabs widget is still displaying as a list. I've linked the correct JS UI and CSS. I've looked over the documentation a hundred times and cannot see what I'm missing. It has to be an incorrect link I guess. The Tabs are displaying as lists.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Reservation request</title>
<link rel="stylesheet" href="main.css">
<script src="https://code.jquery.com/jquery-3.1.1.min.js"></script>
<script src="reservationTab.js"></script>
</head>
<body>
<h1>Reservation Request</h1>
<form action="response.html" method="get"
name="reservation_form" id="reservation_form">
<div id ="tabs">
<ul>
<li> General Information </li>
<li> Preferences </li>
<li> Contact </li>
</ul>
<div id="tabs-1">
<label for="arrival_date">Arrival date:</label>
<input type="text" name="arrival_date" id="arrival_date" placeholder="M/D/YYYY" autofocus>
<span>*</span><br>
<label for="nights">Nights:</label>
<input type="text" name="nights" id="nights">
<span>*</span><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>
</div><!--tab1: genInfo-->
<div id="tabs-2">
<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>
</div> <!--tab2: Pref-->
<div id="tabs-3">
<label for="name">Name:</label>
<input type="text" name="name" id="name">
<span>*</span><br>
<label for="email">Email:</label>
<input type="text" name="email" id="email">
<span>*</span><br>
<label for="phone">Phone:</label>
<input type="text" name="phone" id="phone" placeholder="999-999-9999">
<span>*</span><br>
</div> <!--tab3: contactInfo-->
</div> <!--end tabs div-->
<input type="button" id="policies" value="View Cancellation Policies">
<input type="submit" id="submit" value="Submit Request">
<div id="dialog" title="Cancellation Policies" style="display: none;">
<p>Notification of cancellation or arrival date change must be
received more than three days (72 hours) prior to the confirmed arrival date for the
reservation deposit to be refundable. Email notification is acceptable, and a cancellation
confirmation will be sent to you. Failure to check-in on the scheduled arrival date
will result in the cancellation of the reservation including any remaining nights,
and the reservation deposit shall be forfeited.</p>
</div><br>
</form>
</body>
</html>
JS
$(document).ready(function() {
var emailPattern = /\b[A-Za-z0-9._%+-]+#[A-Za-z0-9.-]+\.[A-Za-z]{2,4}\b/;
// move the focus to the first text box
$("#arrival_date").focus();
//for tabs
$("#tabs").tabs();
// the handler for the submit event of the form
// executed when the submit button is clicked
$("#reservation_form").submit(
function(event) {
var isValid = true;
// validate the requested arrival date
var arrivalDate = $("#arrival_date").val().trim();
if (arrivalDate == "") {
$("#arrival_date").next().text("This field is required.");
isValid = false;
} else {
$("#arrival_date").next().text("");
}
$("#arrival_date").val(arrivalDate);
// validate the number of nights
var nights = $("#nights").val().trim();
if (nights == "") {
$("#nights").next().text("This field is required.");
isValid = false;
} else if (isNaN($("#nights").val())) {
$("#nights").next().text("This field must be numeric.");
isValid = false;
} else {
$("#nights").next().text("");
}
$("#nights").val(nights);
// validate the name entry
var name = $("#name").val().trim();
if (name == "") {
$("#name").next().text("This field is required.");
isValid = false;
}
else {
$("#name").val(name);
$("#name").next().text("");
}
$("#name").val(name);
// validate the email entry with a regular expression
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("");
}
$("#email").val(email);
// validate the phone number
var phone = $("#phone").val().trim();
if (phone == "") {
$("#phone").next().text("This field is required.");
isValid = false;
} else {
$("#phone").next().text("");
}
$("#phone").val(phone);
// prevent the submission of the form if any entries are invalid
if (isValid == false) {
event.preventDefault();
}
} // end function
); // end submit
}); // end ready
Try this:
$(document).ready(function() {
var emailPattern = /\b[A-Za-z0-9._%+-]+#[A-Za-z0-9.-]+\.[A-Za-z]{2,4}\b/;
// move the focus to the first text box
$("#arrival_date").focus();
//for tabs
$("#tabs").tabs();
// the handler for the submit event of the form
// executed when the submit button is clicked
$("#reservation_form").submit(
function(event) {
var isValid = true;
// validate the requested arrival date
var arrivalDate = $("#arrival_date").val().trim();
if (arrivalDate == "") {
$("#arrival_date").next().text("This field is required.");
isValid = false;
} else {
$("#arrival_date").next().text("");
}
$("#arrival_date").val(arrivalDate);
// validate the number of nights
var nights = $("#nights").val().trim();
if (nights == "") {
$("#nights").next().text("This field is required.");
isValid = false;
} else if (isNaN($("#nights").val())) {
$("#nights").next().text("This field must be numeric.");
isValid = false;
} else {
$("#nights").next().text("");
}
$("#nights").val(nights);
// validate the name entry
var name = $("#name").val().trim();
if (name == "") {
$("#name").next().text("This field is required.");
isValid = false;
}
else {
$("#name").val(name);
$("#name").next().text("");
}
$("#name").val(name);
// validate the email entry with a regular expression
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("");
}
$("#email").val(email);
// validate the phone number
var phone = $("#phone").val().trim();
if (phone == "") {
$("#phone").next().text("This field is required.");
isValid = false;
} else {
$("#phone").next().text("");
}
$("#phone").val(phone);
// prevent the submission of the form if any entries are invalid
if (isValid == false) {
event.preventDefault();
}
} // end function
); // end submit
}); // end ready
body {
font-family: Arial, Helvetica, sans-serif;
font-size: 87.5%;
background-color: white;
margin: 0 auto;
width: 600px;
border: 3px solid blue;
padding: 10px 20px;
}
legend {
color: blue;
font-weight: bold;
margin-bottom: .8em;
}
label {
float: left;
width: 100px;
}
input, select {
margin-left: 1em;
margin-right: 1em;
margin-bottom: .5em;
}
input {
width: 14em;
}
input.left {
width: 1em;
padding-left: 0;
}
fieldset {
border: none;
margin-left: 0;
margin-top: 1em;
padding: 0;
}
input.last {
margin-bottom: 1em;
}
#adults, #children {
width: 35px;
}
#smoking {
width: 1em;
margin-left: 0;
}
#policies {
margin-left: 0;
width: 15em;
}
#submit {
width: 10em;
}
#dialog p {
font-size: 85%;
}
span {
color: red;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Reservation request</title>
<!-- jQuery library -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<!-- jQuery UI library -->
<link rel="stylesheet" href="https://ajax.googleapis.com/ajax/libs/jqueryui/1.12.1/themes/smoothness/jquery-ui.css">
<script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.js"></script>
</head>
<body>
<h1>Reservation Request</h1>
<form action="response.html" method="get"
name="reservation_form" id="reservation_form">
<div id ="tabs">
<ul>
<li> General Information </li>
<li> Preferences </li>
<li> Contact </li>
</ul>
<div id="tabs-1">
<label for="arrival_date">Arrival date:</label>
<input type="text" name="arrival_date" id="arrival_date" placeholder="M/D/YYYY" autofocus>
<span>*</span><br>
<label for="nights">Nights:</label>
<input type="text" name="nights" id="nights">
<span>*</span><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>
</div><!--tab1: genInfo-->
<div id="tabs-2">
<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>
</div> <!--tab2: Pref-->
<div id="tabs-3">
<label for="name">Name:</label>
<input type="text" name="name" id="name">
<span>*</span><br>
<label for="email">Email:</label>
<input type="text" name="email" id="email">
<span>*</span><br>
<label for="phone">Phone:</label>
<input type="text" name="phone" id="phone" placeholder="999-999-9999">
<span>*</span><br>
</div> <!--tab3: contactInfo-->
</div> <!--end tabs div-->
<input type="button" id="policies" value="View Cancellation Policies">
<input type="submit" id="submit" value="Submit Request">
<div id="dialog" title="Cancellation Policies" style="display: none;">
<p>Notification of cancellation or arrival date change must be
received more than three days (72 hours) prior to the confirmed arrival date for the
reservation deposit to be refundable. Email notification is acceptable, and a cancellation
confirmation will be sent to you. Failure to check-in on the scheduled arrival date
will result in the cancellation of the reservation including any remaining nights,
and the reservation deposit shall be forfeited.</p>
</div><br>
</form>
<script src="reservationTab.js"></script>
</body>
</html>

JQuery won't change HTML of an id

So I have a form and a script:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form action="" id="contact">
<label for="prenom">Prénom</label>
<input type="text" id="prenom" name="prenom" placeholder="Votre prénom.." class="champ">
<label for="nom">Nom</label>
<input type="text" id="nom" name="nom" placeholder="Votre nom.." class="champ"><br/>
<label for="email">Email</label>
<input type="text" id="email" name="email" placeholder="Votre nom.." class="champ"><br/>
<label for="country">Pays</label>
<select name="country" id="country" class="champ">
<option value="france">France</option>
<option value="Canada">Canada</option>
<option value="Suisse">Suisse</option>
<option value="Belgique">Belgique</option>
</select><br/>
<label for="sujet">Sujet : </label>
<textarea class="champ" name="sujet" id="sujet" placeholder="Exprimez-vous.." style="height:200px; width=600px;"></textarea ><br/>
<input type="submit" value="Envoyer" class="champ" id="envoi">
</form>
<div id="errorMessage"></div>
<script type="text/javascript">
var errorMessage="";
$("#envoi").click(function () {
if($("#prenom").val()==""){
errorMessage+="<p>Remplissez votre prénom!</p>";
}
if($("#nom").val()==""){
errorMessage+="<p>Remplissez votre nom!</p>";
}
if($("#email").val()==""){
errorMessage+="<p>Remplissez votre email!</p>";
}
if($("#pays").val()==""){
errorMessage+="<p>Sélectionnez votre pays!</p>";
}
if($("#sujet").val()==""){
errorMessage+="<p>Remplissez votre message!</p>";
}
if(errorMessage!=""){
alert("hey");
$("#errorMessage").html(errorMessage);
}
});
</script>
I have a problem with this :
if(errorMessage!=""){
alert("hey");
$("#errorMessage").html(errorMessage);
}
I wish it would display the error message in
right before the script. The program does get into the if condition, because the alert appears. However, it does not display the error.
What am I doing wrong please?
Thanks,
It's due to your page is being reloaded after being submitted.
If you want to display an error (validation) you should return false.
if(errorMessage!=""){
alert("hey");
$("#errorMessage").html(errorMessage);
return false;
}
simply just add the following in your code to Acheive your goal
e.preventDefault();
Here is the working jsfiddle:https://jsfiddle.net/1b5pcqpL/
The button trigger you are using is of type=submit which is causing your form to submit.
Instead try using type=button and submit the form after jquery validation.
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form action="" id="contact">
<label for="prenom">Prénom</label>
<input type="text" id="prenom" name="prenom" placeholder="Votre prénom.." class="champ">
<label for="nom">Nom</label>
<input type="text" id="nom" name="nom" placeholder="Votre nom.." class="champ"><br/>
<label for="email">Email</label>
<input type="text" id="email" name="email" placeholder="Votre nom.." class="champ"><br/>
<label for="country">Pays</label>
<select name="country" id="country" class="champ">
<option value="france">France</option>
<option value="Canada">Canada</option>
<option value="Suisse">Suisse</option>
<option value="Belgique">Belgique</option>
</select><br/>
<label for="sujet">Sujet : </label>
<textarea class="champ" name="sujet" id="sujet" placeholder="Exprimez-vous.." style="height:200px; width=600px;"></textarea ><br/>
<input type="button" value="Envoyer" class="champ" id="envoi">
</form>
<div id="errorMessage"></div>
<script type="text/javascript">
$("#envoi").click(function () {
var errorMessage="";
if($("#prenom").val()==""){
errorMessage+="<p>Remplissez votre prénom!</p>";
}
if($("#nom").val()==""){
errorMessage+="<p>Remplissez votre nom!</p>";
}
if($("#email").val()==""){
errorMessage+="<p>Remplissez votre email!</p>";
}
if($("#pays").val()==""){
errorMessage+="<p>Sélectionnez votre pays!</p>";
}
if($("#sujet").val()==""){
errorMessage+="<p>Remplissez votre message!</p>";
}
if(errorMessage!=""){
alert("hey");
$("#errorMessage").html(errorMessage);
}
else{
$("#contact").submit();
}
});
</script>
The message is appended to the DOM, what happens is that the form get submitted and that causing the page to reload (happens so fast you can't notice it). You'll have to prevent the default behavior of the event (which is submitting the form right after the alert and the message is appended to the DOM)!
Note: Change your click event to the submit event to prevent the user from submitting via enter key as well.
<script type="text/javascript">
$("#contact").submit(function (event) { // listen to the submit event on the form #contact itself (event is needed so we can prevent its default behavior)
var errorMessage = ""; // this should be here
// ...
if(errorMessage != ""){
alert("hey");
$("#errorMessage").html(errorMessage);
event.preventDefault(); // stop the submit (we encountered an error so mission abort :D)
}
});
</script>
<head>
<title>jQuery</title>
<script type="text/javascript" src="jquery.min.js"></script>
<style type="text/css">
body {
font-family: helvetica, sans-serif;
font-size:130%;
}
input {
padding: 5px 5px 12px 5px;
font-size: 25px;
border-radius: 5px;
border: 1px solid grey;
width:320px;
}
label {
position: relative;
top:12px;
width:200px;
float: left;
}
#wrapper {
width: 550px;
margin: 0 auto;
}
.form-element {
margin-bottom: 10px;
}
#submitButton {
width: 130px;
margin-left: 200px;
}
#errorMessage {
color: red;
font-size: 90% !important;
}
#successMessage {
color: green;
font-size: 90% !important;
display:none;
margin-bottom:20px;
}
</style>
</head>
<body>
<div id="wrapper">
<div id="successMessage">You've done it! Congratulations.</div>
<div id="errorMessage"></div>
<div class="form-element">
<label for="email">Email</label>
<input type="text" name="email" id="email" placeholder = "eg. yourname#gmail.com">
</div>
<div class="form-element">
<label for="phone">Telephone</label>
<input type="text" name="phone" id="phone" placeholder = "eg. 0123456789">
</div>
<div class="form-element">
<label for="password">Password</label>
<input type="password" name="password" id="password">
</div>
<div class="form-element">
<label for="passwordConfirm">Confirm Password</label>
<input type="password" name="passwordConfirm" id="passwordConfirm">
</div>
<div class="form-element">
<input type="submit" id="submitButton" value="Sign Up"
</div>
</div>
<script type="text/javascript">
function isEmail(email) {
var regex = /^([a-zA-Z0-9_.+-])+\#(([a-zA-Z0-9-])+\.)+([a-zA-Z0-9]{2,4})+$/;
return regex.test(email);
}
$("#submitButton").click(function() {
var errorMessage = "";
var fieldsMissing = "";
if ($("#email").val() == "") {
fieldsMissing += "<br>Email";
}
if ($("#phone").val() == "") {
fieldsMissing += "<br>Telephone";
}
if ($("#password").val() == "") {
fieldsMissing += "<br>Password";
}
if ($("#passwordConfirm").val() == "") {
fieldsMissing += "<br>Confirm Password";
}
if (fieldsMissing != "") {
errorMessage += "<p>The following field(s) are missing:" + fieldsMissing;
}
if (isEmail($("#email").val()) == false) {
errorMessage += "<p>Your email address is not valid</p>";
}
if ($.isNumeric($("#phone").val()) == false) {
errorMessage += "<p>Your phone number is not numeric</p>"
}
if ($("#password").val() != $("#passwordConfirm").val()) {
errorMessage += "<p>Your passwords don't match</p>";
}
if (errorMessage != "") {
$("#errorMessage").html(errorMessage);
} else {
$("#successMessage").show();
$("#errorMessage").hide();
}
});
</script>
</body>
How come it works in this case?

How do I enable my form's submit button using jquery?

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;
}

Javascript not working to validate a form in HTML

Hi i'm having trouble trying to validate a simple form. I'm not the best at Javascript and am unsure where i'm going wrong. It may be a simple speelling mistake or a complete clash between my code that i can't see. All help is appreciated. Sorry for the big chunk of code, i wanted to make sure you see every detail.
<!DOCTYPE html>
<html>
<head>
<link rel = "stylesheet"
type = "text/css"
href = "Stylesheet.css" />
<title>Customer details form</title>
<script src="gen_validatorv4.js" type="text/javascript"></script>
<!-- ============================== My failed attempt to try and validate my form with Javascript ============================== -->
<script>
function check() {
document.getElementById("Agree").checked = true;
}
function uncheck() {
document.getElementById("Agree").checked = false;
}
</script>
<center><img src= Images/HorizonHomePageTitle.png ALT="Horizon Bed and Breakfast Title"></center>
</head>
<body>
<script>
window.alert(Please enter data where * is assigned.);
</script>
<center>Budget Rooms<center>
<HR COLOR="blue" WIDTH="60%">
<center>Luxury Rooms<center>
<HR COLOR="blue" WIDTH="60%">
<center>Home<center>
<HR COLOR="blue" WIDTH="60%">
<center>Our privacy policy<center>
<HR COLOR="blue" WIDTH="60%">
<center>Our terms of conditions<center>
<HR COLOR="blue" WIDTH="60%">
<center>Our terms and conditions<center>
<HR COLOR="blue" WIDTH="60%">
<center>Contact us<center>
<form id='CustomerDetailForm' action="">
<!-- ============================== Fieldset 1 - includes personal information of clients ============================== -->
<fieldset>
<legend>Personal Information:</legend>
<hr class="form" />
<label for="Full Name"><strong>Full Name:*</strong></label>
<input name="FullNm" type="text" size="20" id="FN" class="text"/>
<label for="Email"><strong>Email:</strong></label><br/>
<input name="Emil" type="text" size="20" id="EM" class="text"/>
<label for="Age"><strong>Input age if between 18 and 100:</strong></label>
<input name="Ages" type="text" size="20" id="AG" class="text"/>
<label for="select" class="choose"><strong>On what continent do you live?</strong></label>
<select id="select" name="select">
<option value="1">Africa</option>
<option value="2">Europe</option>
<option value="3">Asia</option>
<option value="4">North Amrica</option>
<option value="5">South America</option>
<option value="6">Ausralia</option>
</select>
</fieldset>
<!-- ============================== Fieldset 2 - Includes further optional information from clients to help productivity ============================== -->
<fieldset>
<legend>Questions:</legend>
<hr class="form" />
<label for="select2" class="choose">How long was your stay?</label><br />
<select id="select" name="select2">
<option value="7">Less than one week</option>
<option value="8">More than one week</option>
<option value="9">Months/years</option>
</select>
<label for="select3" class="choose">How many stars would you rate our BnB?</label><br />
<select id="selectCon" name="select3">
<option value="10">One star</option>
<option value="11">Two star</option>
<option value="12">Three star</option>
<option value="13">Four star</option>
<option value="14">Five star</option>
</select>
</fieldset>
<!-- ============================== Fieldset 3 - Holds the comments section, aggreement radio button, submit button and a date button for the client ============================== -->
<fieldset>
<legend>Further commetns:</legend>
<hr class="form" />
<textarea name="message" id="message" cols="20" rows="10"></textarea><br />
<label for="protection" class="spam-protection">Spam check: 1 + 1=</label><br />
<input name="ochrana" type="text" id="protection" class="answer" /><br />
Do you agree to our terms?*<br>
<input type="radio" name="Agreement" id="Agree">Agree<br>
<button onclick="formValidation()">SUBMIT</button>
<script>
function submitFunction() {
alert("Thankyou for your submission");
}
</script>
<script>
function formValidation()
{
var uname = document.registration.FullNm;
var uemail = document.registration.Emil;
var uage = document.registration.Ages;
var ucon = document.registration.select;
{
if(nameinput(FullName,2,25))
{
if(emailval(uemail))
{
if(agenum(ag))
{
if(conselect(con))
{
}
}
}
}
}
}
}
}
return false;
}
function nameinput(uname,2,25)
{
var uname_len = uname.value.length;
if (uname_len == 0 || uname_len >= 2 || uname_len < 25)
{
alert("Full Name is needed. Between "+2+" to "+25" characters.);
uname.focus();
return false;
}
return true;
}
function emailval(uemail,2,25)
{
var uemail_len = uemail.value.length;
if (uemail_len == 0 || uemail_len >= 2 || uemail_len < 30)
{
alert("Email is required.");
uemail.focus();
return false;
}
return true;
}
function agenum(uage,18,100)
{
var uage_len = uage.value.length;
if (uage_len == 0 || uage_len >= 18 || uage_len < 100)
{
alert("Age is required. Between 18 and 100.");
uage.focus();
return false;
}
return true;
}
function conselect(ucon)
{
if(ucon.value == "Default")
{
alert('Select your continent from the list');
ucon.focus();
return false;
}
else
{
return true;
}
}
</script>
</form>
<button type="button"
onclick="document.getElementById('date/time').innerHTML = Date()">
Display date and time.</button>
<p id="date/time"></p>
</fieldset>
</form>
</body>
</html>
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" type="text/css" href="Stylesheet.css" />
<title>Customer details form</title>
<script src="gen_validatorv4.js" type="text/javascript"></script>
<!-- ============================== My failed attempt to try and validate my form with Javascript ============================== -->
<script type="text/javascript">
function check() {
document.getElementById("Agree").checked = true;
}
function uncheck() {
document.getElementById("Agree").checked = false;
}
function formValidation() {
var uname = document.getElementById("FullNm");
var uemail = document.getElementById("Email");
var uage = document.getElementById("Ages");
var ucon = document.getElementById("select1");
if (nameInput(uname)) {
if (emailVal(uemail)) {
if (ageNum(uage)) {
if (conSelect(ucon)) {
}
}
}
}
}
function nameInput(uname) {
var uname_len = uname.value.length;
if (uname_len == 0 || uname_len <= 2 || uname_len > 25) {
alert("Full Name is needed. Between 2 to 25 characters.");
uname.focus();
return false;
}
else {
return true;
}
}
function emailVal(uemail) {
var uemail_len = uemail.value.length;
if (uemail_len == 0) {
alert('Email is required');
return false;
}
else {
return true;
}
}
function ageNum(uage) {
var age = uage.value;
if (age == 0 || age < 18 || age > 100) {
alert("Age is required. Between 18 and 100.");
uage.focus();
return false;
}
else
return true;
}
function conSelect(ucon) {
if (ucon.value == 0) {
alert('Select your continent from the list');
ucon.focus();
return false;
}
else {
return true;
}
}
</script>
<center>
<img src="Images/HorizonHomePageTitle.png" alt="Horizon Bed and Breakfast Title"></center>
</head>
<body>
<center>
Budget Rooms<center>
<hr color="blue" width="60%">
<center>
Luxury Rooms<center>
<hr color="blue" width="60%">
<center>
Home<center>
<hr color="blue" width="60%">
<center>
<a href="https://www.visser.com.au/blog/generic-privacy-policy-for-australian-websites/"
target="_blank">Our privacy policy</a><center>
<hr color="blue" width="60%">
<center>
<a href="https://media.termsfeed.com/pdf/terms-and-conditions-template.pdf" target="_blank">
Our terms of conditions</a><center>
<hr color="blue" width="60%">
<center>
<a href=" http://www.blogtyrant.com/best-about-us-pages/" target="_blank">Our terms
and conditions</a><center>
<hr color="blue" width="60%">
<center>
Contact us<center>
<form id='CustomerDetailForm' action="">
<!-- ============================== Fieldset 1 - includes personal information of clients ============================== -->
<fieldset>
<table>
<tr>
<td colspan="2">
<legend>Personal Information:</legend>
</td>
</tr>
<tr>
<td>
<label for="Full Name">
<strong>Full Name:*</strong></label>
</td>
<td>
<input id="FullNm" name="FullNm" type="text" size="20" class="text" />
</td>
</tr>
<tr>
<td>
<label for="Email">
<strong>Email:</strong></label><br />
</td>
<td>
<input id="Email" name="Email" type="text" size="20" class="text" />
</td>
</tr>
<tr>
<td>
<label for="Age">
<strong>Input age if between 18 and 100:</strong></label>
</td>
<td>
<input name="Ages" type="text" size="20" id="Ages" class="text" />
</td>
</tr>
<tr>
<td>
<label for="select" class="choose">
<strong>On what continent do you live?</strong></label>
</td>
<td>
<select id="select1" name="select">
<option value="0">Select</option>
<option value="1">Africa</option>
<option value="2">Europe</option>
<option value="3">Asia</option>
<option value="4">North Amrica</option>
<option value="5">South America</option>
<option value="6">Ausralia</option>
</select>
</td>
</tr>
</table>
</fieldset>
<!-- ============================== Fieldset 2 - Includes further optional information from clients to help productivity ============================== -->
<fieldset>
<legend>Questions:</legend>
<hr class="form" />
<label for="select2" class="choose">
How long was your stay?</label><br />
<select id="select" name="select2">
<option value="7">Less than one week</option>
<option value="8">More than one week</option>
<option value="9">Months/years</option>
</select>
<label for="select3" class="choose">
How many stars would you rate our BnB?</label><br />
<select id="selectCon" name="select3">
<option value="10">One star</option>
<option value="11">Two star</option>
<option value="12">Three star</option>
<option value="13">Four star</option>
<option value="14">Five star</option>
</select>
</fieldset>
<!-- ============================== Fieldset 3 - Holds the comments section, aggreement radio button, submit button and a date button for the client ============================== -->
<fieldset>
<legend>Further commetns:</legend>
<hr class="form" />
<textarea name="message" id="message" cols="20" rows="10"></textarea><br />
<label for="protection" class="spam-protection">
Spam check: 1 + 1=</label><br />
<input name="ochrana" type="text" id="protection" class="answer" /><br />
Do you agree to our terms?*<br>
<input type="radio" name="Agreement" id="Agree">Agree<br>
<button onclick="formValidation();">
SUBMIT</button>
</fieldset>
</form>
<script type="text/javascript">
function submitFunction() {
alert("Thankyou for your submission");
}
</script>
<button type="button" onclick="document.getElementById('date/time').innerHTML = Date()">
Display date and time.</button>
<p id="date/time">
</p>
</body>
</html>

Categories

Resources