JQuery won't change HTML of an id - javascript

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?

Related

How show basic validation messages in the text field

I want to show the validation messages below the text fields that require it as well as the example that is in the image that I found
Example
I have the following text fields on my form, with their respective validation done in Javascript
//Function to validate ticket form
function validate_form() {
valid = true;
if (document.ticketForm.matricula.value == "") {
alert("Verify the data again, enter the license plate");
valid = false;
}
if (document.ticketForm.nombre.value == "") {
alert("Verify the data again, enter the name of the applicant");
valid = false;
}
return valid;
}
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">
<form name="ticketForm" method="post" onchange="validate_form();">
<div id="informacionTicket" class="user">
<div class="card shadow mb-4">
<div class="card-body">
<div class="mb-4">
<div class="form-group">
<label for="ticketIdAppliInput">License:</label>
<input maxlength="9" required id="ticketIdAppliInput" type="text" name="matricula" onkeypress="if (isNaN(String.fromCharCode(event.keyCode))) return false;" class="form-control form-control-user" />
</div>
<div class="form-group">
<label for="ticketNameAppliInput">Full name:</label>
<input maxlength="100" id="ticketNameAppliInput" type="text" name="nombre" class="form-control form-control-user" />
</div>
<div class="form-group">
<label for="ticketEmailAppliInput">Email:</label>
<input maxlength="100" id="ticketEmailAppliInput" type="email" name="email" class="form-control form-control-user" />
</div>
</div>
</div>
</div>
</div>
<button type="button" id="submit" class="btn btn-primary btn-user btn-block">Send</button>
</form>
What I don't want is to be shown those annoying alert at the top of the form
I want the message to be displayed as in the example image
UPDATE:
Try this possible solution but when entering a value the message is no longer deleted
UPDATE:
I tried the possible solution of #JarlikStepsto but it still doesn't work properly
function validate(field) {
const validateables = document.getElementsByClassName('validateable');
const input = field;
if (!input.value == "") {
input.classList.add('invalid');
} else {
input.classList.remove('invalid');
}
if (!input.value == "") {
input.classList.add('invalid');
} else {
input.classList.remove('invalid');
}
}
input {
display: block;
}
.validation-message {
display: none;
}
input.validateable.invalid + .validation-message {
display: block;
color: red;
}
<div class="form-group">
<label class="required-field" name="matricula" for="ticketIdAppliInput">Matrícula:</label>
<input onchange="validate(this)" maxlength="9" required="required" id="ticketIdAppliInput" type="text" name="matricula" onkeypress="if (isNaN(String.fromCharCode(event.keyCode))) return false;" class="form-control form-control-user validateable"/>
<div class="validation-message">
Verifique la información nuevamente, ingrese la matricula</div>
</div>
<div class="form-group">
<label class="required-field" name="nombre" for="ticketNameAppliInput">Nombre completo:</label>
<input onchange="validate(this)" maxlength="100" id="ticketNameAppliInput" type="text" name="nombre" class="form-control form-control-user validateable" />
<div class="validation-message">
Verifique la información nuevamente, ingrese el nombre
</div>
</div>
UPDATE 2:
I will explain it better, I have two fields that matter to me that are compulsory "Matricula" and "Nombre Completo", when I am filling out the third field I do not get the validation message, this is the code I have, will I be doing something wrong?
function validate(field) {
const input = field;
if (!input.value || input.value.length === 0) {
input.classList.add('invalid');
} else {
input.classList.remove('invalid');
}
}
input {
display: block;
}
.validation-message {
display: none;
}
input.validateable.invalid + .validation-message {
display: block;
color: red;
}
<div class="form-group">
<label class="required-field" name="matricula" for="ticketIdAppliInput">Matrícula:</label>
<input onchange="validate(this)" maxlength="9" id="ticketIdAppliInput" type="text" name="matricula" onkeypress="if (isNaN(String.fromCharCode(event.keyCode))) return false;" class="form-control form-control-user validateable"/>
<div class="validation-message">
Verifique la información nuevamente, ingrese la matricula</div>
</div>
<div class="form-group">
<label class="required-field" name="nombre" for="ticketNameAppliInput">Nombre completo:</label>
<input onchange="validate(this)" maxlength="100" id="ticketNameAppliInput" type="text" name="nombre" class="form-control form-control-user validateable" />
<div class="validation-message">
Verifique la información nuevamente, ingrese el nombre
</div>
</div>
<div class="form-group">
<label class="required-field" name="email" for="ticketEmailAppliInput">Email:</label>
<input onchange="validate(this)" maxlength="100" id="ticketEmailAppliInput" type="email" name="email" class="form-control form-control-user validateable" />
<div class="validation-message">
Verifique la información nuevamente, ingrese el correo electronico
</div>
</div>
To show a validation message under the field you need a element to display it.
It could be any div, span or whatever you want.
In my example i will use a span to demonstrate how it works:
<input onchange="validate();" type="text" class="validateable" validation-pattern="[0-9]*" />
<div class="validation-message">Only numbers are allowed in this field!</div>
now in the js code we just have to validate for the pattern and set a input to invalid if it does not match the pattern:
function validate(){
const validateables = document.getElementsByClassName('validateable');
Array.prototype.forEach.call(validateables, input => {
const pattern = input.getAttribute('validation-pattern');
if(!input.value.match('^' + pattern + '$')){
input.classList.add('invalid');
} else {
input.classList.remove('invalid');
}
});
}
and the css to display validation text only if invalid:
.validation-message {
display: none;
}
input.validateable.invalid + .validation-message{
display: block;
color: red;
}
What this code does:
The JS function looks for every input with the class "validateable" and iterates over them. Each element should have an attribute with an validation pattern validation-pattern="[0-9]*" Now the function checks, if the value of the input matches the pattern and add a class invalid to the input or removes it.
In the css i defined an invisible div validation-message but if the element bevor this div is an validateable input field, that is invalid, the div will be displayed and you can see the validation message.
Working fidle:
https://jsfiddle.net/h687eomf/
UPDATE:
in your case, you just want to validate the field, that you are changing, have a look at my changed example fidle:
https://jsfiddle.net/h687eomf/2/
UPDATE 2:
A try to fix your snippet, assuming that a field is valid when its value is not empty and invalid if the value is empty:
function validate(field) {
const input = field;
if (!input.value || input.value.length === 0) {
input.classList.add('invalid');
} else {
input.classList.remove('invalid');
}
}
input {
display: block;
}
.validation-message {
display: none;
}
input.validateable.invalid + .validation-message {
display: block;
color: red;
}
<div class="form-group">
<label class="required-field" name="matricula" for="ticketIdAppliInput">Matrícula:</label>
<input onchange="validate(this)" maxlength="9" required="required" id="ticketIdAppliInput" type="text" name="matricula" onkeypress="if (isNaN(String.fromCharCode(event.keyCode))) return false;" class="form-control form-control-user validateable"/>
<div class="validation-message">
Verifique la información nuevamente, ingrese la matricula</div>
</div>
<div class="form-group">
<label class="required-field" name="nombre" for="ticketNameAppliInput">Nombre completo:</label>
<input onchange="validate(this)" maxlength="100" id="ticketNameAppliInput" type="text" name="nombre" class="form-control form-control-user validateable" />
<div class="validation-message">
Verifique la información nuevamente, ingrese el nombre
</div>
</div>

form validation message (dynamic)

Is there a way to dynamically tell which .input has yet to be entered? In the code below you can see that if I enter out of order, the #message
only counts how many inputs have been populated and displays the message listed in order under numValid == 1, 2, 3, etc.
Can the code be changed to dynamically display a message for the .inputs that have not been populated?
*****Example: if I type in the Last Name and Student ID field, the message will either tell me to enter in the First Name or City field, etc. until they are all populated and the last validation (success message) is displayed*****
$("#form input").keyup(function() {
var numValid = 0;
$("#form input[required]").each(function() {
if (this.validity.valid) {
numValid++;
}
});
var progress = $("#progress"),
progressMessage = $("#message");
if (numValid == 1) {
progress.attr("value", "25");
progressMessage.text("Please Enter the First Name.");
}
if (numValid == 2) {
progress.attr("value", "50");
progressMessage.text("Please Enter the Last Name.");
}
if (numValid == 3) {
progress.attr("value", "75");
progressMessage.text("Please Enter a City.");
}
if (numValid == 4) {
progress.attr("value", "100");
progressMessage.text("You're done, post!");
}
});
#mainformdiv {
margin-left: auto;
margin-right: auto;
width: 500px;
border: 1px solid;
border-radius: 10px;
}
#form {
padding: 20px;
}
#progress {
width: 460px;
height: 25px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="mainformdiv">
<form id="form">
<div id="progressdiv">
<progress max="100" value="0" id="progress"></progress>
<div id="message">Progress Message...</div>
</div>
<div class="input">
<label for="userid">Student ID</label><br>
<input id="userid" required="required" type="text">
</div>
<div class="input">
<label for="firstname">First Name</label><br>
<input id="firstname" required="required" type="text">
</div>
<div class="input">
<label for="lastname">Last Name</label><br>
<input id="lastname" required="required" type="text">
</div>
<div class="input">
<label for="city">City</label><br>
<input id="city" required="required" type="text"></br>
</div>
</form>
</div>
Easy to accomplish, just iterate over all of the required fields, and join their ids into a string. If you want to display a nicer looking name, then just map the IDs to an object first.
$("#form input").keyup(function() {
var numValid = 0;
$("#form input[required]").each(function() {
if (this.validity.valid) {
numValid++;
}
});
var progress = $("#progress"),
progressMessage = $("#message");
const invalidInputs = Array.from(document.querySelectorAll('#form input[required]'))
.filter(input => !input.validity.valid)
.map(input => input.id);
progress.attr("value", numValid * 25);
if (numValid == 4) {
progressMessage.text("You're done, post!");
} else {
progressMessage.text('Please fill out the following fields: ' + invalidInputs.join(', '));
}
});
#mainformdiv {
margin-left: auto;
margin-right: auto;
width: 500px;
border: 1px solid;
border-radius: 10px;
}
#form {
padding: 20px;
}
#progress {
width: 460px;
height: 25px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="mainformdiv">
<form id="form">
<div id="progressdiv">
<progress max="100" value="0" id="progress"></progress>
<div id="message">Progress Message...</div>
</div>
<div class="input">
<label for="userid">Student ID</label><br>
<input id="userid" required="required" type="text">
</div>
<div class="input">
<label for="firstname">First Name</label><br>
<input id="firstname" required="required" type="text">
</div>
<div class="input">
<label for="lastname">Last Name</label><br>
<input id="lastname" required="required" type="text">
</div>
<div class="input">
<label for="city">City</label><br>
<input id="city" required="required" type="text"></br>
</div>
</form>
</div>

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 addClass working in a very odd manner

I have a form with 3 inputs: 2 text inputs for a Username and E-mail and a third password input for, you guessed it, a password.
I'm validating these input fields in JQuery and when an input is either empty or doesn't match it's format, it adds a class to the input with a red border. The code goes as follows:
if ($("input#username").val().length < 6) {
$("input#username").addClass('input-error');
next_step = false;
} else if (!isEmail($("#email").val())) {
$("#email").addClass('input-error');
next_step = false;
} else if (!isPassword($("#pwd").val())) {
$("#pwd").addClass('input-error');
next_step = false;
}
else {
$(this).removeClass('input-error');
next_step = true;
}
It works perfectly with both Username and E-mail fields, and it also works if the Password field is empty, but even though it validates perfectly, the addClass() doesn't work if the Password doesn't meet it's requirements (At least one Uppercase letter and one number).
This is what the browser console shows:
As you can see, it kind of adds the class, but then not really.
What is happening? If you need the HTML code and/or the CSS code, tell me!
Thanks for your attention!
EDIT
Here is the HTML and CSS as requested:
<fieldset>
<div class="form-bottom">
<img src="img/gbsnlogo.svg" alt="GBSN Research" name="GBSN Research" width="50%" class="signupLogo" />
<br>
<br>
<br>
<div class="form-group">
<label for="username"><h1>USERNAME:</h1></label>
<input type="text" class="form-control" id="username" placeholder="Enter username..." name="username">
</div>
<div class="form-group">
<label for="email"><h1>E-MAIL:</h1></label>
<input type="text" class="form-control" id="email" placeholder="Enter e-mail..." name="email">
</div>
<div class="form-group">
<label for="pwd"><h1>PASSWORD:</h1></label>
<input type="password" class="form-control" id="pwd" placeholder="Enter password..." name="pwd">
</div>
<div class="text-center">
<button type="button" class="btn-next btn-nav"><h1>NEXT</h1></button>
</div>
</div>
</fieldset>
and the CSS:
.form-control {
height: 40px;
border: 2px solid black;
border-radius: 0;
font-size: 14px;
}
.form-control:focus {
border: 2px solid black;
box-shadow: 0;
}
.input-error {
border-color: #FF2859;
}
This is working for me.
Please comment what is still not working if you have this kind of setup?
function isEmail(email) { // dummy example
return email.indexOf("#")>1;
}
function isPassword(passwd) { // dummy example
return passwd.indexOf("x")>=0; // must contain x
}
$(function() {
$(".btn-next").on("click", function() {
$(".form-group input").removeClass('input-error');
var next_step = true,
user = $("#username").val(),
email = $("#email").val(),
pwd=$("#pwd").val();
if (user.length < 6) {
$("#username").addClass('input-error');
next_step = false;
} else if (!isEmail(email)) {
$("#email").addClass('input-error');
next_step = false;
} else if (!isPassword(pwd)) {
$("#pwd").addClass('input-error');
next_step = false;
}
console.log(next_step);
});
});
.form-control {
height: 40px;
border: 2px solid black;
border-radius: 0;
font-size: 14px;
}
.form-control:focus {
border: 2px solid black;
box-shadow: 0;
}
.input-error {
border-color: #FF2859;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<fieldset>
<div class="form-bottom">
<img src="img/gbsnlogo.svg" alt="GBSN Research" name="GBSN Research" width="50%" class="signupLogo" />
<br>
<br>
<br>
<div class="form-group">
<label for="username"><h1>USERNAME:</h1></label>
<input type="text" class="form-control" id="username" placeholder="Enter username..." name="username">
</div>
<div class="form-group">
<label for="email"><h1>E-MAIL:</h1></label>
<input type="text" class="form-control" id="email" placeholder="Enter e-mail..." name="email">
</div>
<div class="form-group">
<label for="pwd"><h1>PASSWORD:</h1></label>
<input type="text" class="form-control" id="pwd" placeholder="Enter password..." name="pwd">
</div>
<div class="text-center">
<button type="button" class="btn-next btn-nav"><h1>NEXT</h1></button>
</div>
</div>
</fieldset>
From what I see from the image you posted
I can only speculate this is what happened.
The line [input#pwd.form-control.input-error] was evaluated immediately when it got printed to the console. So that mean at that time, the dom does have the class input error in it. However, when you expand it, the dom got re-evaluated again. And at that time, the dom's class input-error got removed, so you don't see it anymore. I was able to prove this by running $('#pwd').addClass('input-error') and $('#pwd').removeClass('input-error') in that order, image below
Based on that, I suspect you have another logic in the code that remove the class shortly after you have added the class to the dom, highly possibly $(this).removeClass('input-error');.

Jquery's form serialization sends repeated information

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.

Categories

Resources