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>
Related
I have a form here that I'm trying to get an error message when either 3 boxes are empty when I click submit but it's not working, what am I doing wrong? I put in a onsubmit in my form but still doesnt work
HTML:
var message = document.getElementById("ErrorMessage");
function clearMyField(el) {
if(el.placeholder !='') {
el.placeholder = '';
}
}
function checkforblank() {
var allInputs = document.querySelectorAll('input[type=text]');
for(let i = 0; i<allInputs.length; i++){
let v = allInputs[i].value.trim();
let n = allInputs[i].name;
if(v == ""){
message.textContent = n + " is empty";
return false;
}
}
}
<!doctype html>
<html lang="en">
<head>
<title> Lab 6 - Task 2 </title>
<style>
span {
padding-left: 10px;
display: block;
float: left;
width: 20%;
}
button { margin-left: 10px; }
body {
width: 80%; margin: auto; font-family: sans-serif;
border: 1px solid black;
}
</style>
<meta charset="utf-8">
<script src="prototype.js"></script>
<script src="task2.js"></script>
</head>
<body>
<form id="myForm" method="get" onsubmit="return checkforblank()">
<h1> Form Submit </h1>
<p> <span>Name:</span> <input type="text" id="input1" placeholder="Enter Name" name="Name" onfocus="clearMyField(this);"></p>
<p> <span>Student Id:</span> <input type="text" id="input2" placeholder="Enter Student ID" name="StudentID" onfocus="clearMyField(this);"></p>
<p> <span>Email:</span> <input type="text" id="input3" placeholder="Enter Email" name="Email" onfocus="clearMyField(this);"></p>
<p>
<button id="submitButton" type="submit"> Submit </button>
<input type="reset" value="Reset">
</p>
<p style="color:red" id="ErrorMessage"> </p>
</form>
</body>
</html>
Fix this:
<form id="myForm" method="get" onsubmit="checkforblank()">
</form>
See here
There is no need for return statement
The type of the button should be submit instead of button. Since you are comparing the value inside the function, you have to set the input's placeholder property instead of value
<button id="submitButton" type="submit"> Submit </button>
var message = document.getElementById("ErrorMessage");
function clearMyField(el) {
if(el.placeholder !='') {
el.placeholder = '';
}
}
function checkforblank() {
var allInputs = document.querySelectorAll('input[type=text]');
for(let i = 0; i<allInputs.length; i++){
let v = allInputs[i].value.trim();
let n = allInputs[i].name;
if(v == ""){
message.textContent = n + " is empty";
return false;
}
}
}
span {
padding-left: 10px;
display: block;
float: left;
width: 20%;
}
button { margin-left: 10px; }
body {
width: 80%; margin: auto; font-family: sans-serif;
border: 1px solid black;
}
<form id="myForm" method="get" onsubmit="return checkforblank()">
<h1> Form Submit </h1>
<p> <span>Name:</span> <input type="text" id="input1" placeholder="Enter Name" name="Name" onfocus="clearMyField(this);"></p>
<p> <span>Student Id:</span> <input type="text" id="input2" placeholder="Enter Student ID" name="StudentID" onfocus="clearMyField(this);"></p>
<p> <span>Email:</span> <input type="text" id="input3" placeholder="Enter Email" name="Email" onfocus="clearMyField(this);"></p>
<p>
<button id="submitButton" type="submit"> Submit </button>
<input type="reset" value="Reset">
</p>
<p style="color:red" id="ErrorMessage"> </p>
</form>
Though I will prefer the following:
var message = document.getElementById("ErrorMessage");
function clearMyField(el) {
if(el.placeholder !='') {
el.placeholder = '';
}
}
function checkforblank() {
var allInputs = document.querySelectorAll('input[type=text]');
for(let i = 0; i<allInputs.length; i++){
let v = allInputs[i].value.trim();
let n = allInputs[i].name;
if(v == ""){
return false;
}
}
}
span {
padding-left: 10px;
display: block;
float: left;
width: 20%;
}
button { margin-left: 10px; }
body {
width: 80%; margin: auto; font-family: sans-serif;
border: 1px solid black;
}
<form id="myForm" method="get" onsubmit="return checkforblank()">
<h1> Form Submit </h1>
<p> <span>Name:</span> <input type="text" id="input1" placeholder="Enter Name" name="Name" onfocus="clearMyField(this);" required></p>
<p> <span>Student Id:</span> <input type="text" id="input2" placeholder="Enter Student ID" name="StudentID" onfocus="clearMyField(this);" required></p>
<p> <span>Email:</span> <input type="text" id="input3" placeholder="Enter Email" name="Email" onfocus="clearMyField(this);" required></p>
<p>
<button id="submitButton" type="submit"> Submit </button>
<input type="reset" value="Reset">
</p>
</form>
You can use html5 attributes to do this easily. (required, placeholder attributes)
Try below code.
<!doctype html>
<html lang="en">
<head>
<title> Lab 6 - Task 2 </title>
<style>
span {
padding-left: 10px;
display: block;
float: left;
width: 20%;
}
button { margin-left: 10px; }
body {
width: 80%; margin: auto; font-family: sans-serif;
border: 1px solid black;
}
</style>
<meta charset="utf-8">
</head>
<body>
<form id="myForm" method="get">
<h1> Form Submit </h1>
<p><span>Name:</span> <input id="input1" placeholder="Enter Name" name="Name" required></p>
<p><span>Student Id:</span> <input id="input2" placeholder="Enter Student ID" name="StudentID" required></p>
<p><span>Email:</span> <input id="input3" placeholder="Enter Email" name="Email" required></p>
<p>
<button id="submitButton" type="submit">Submit </button>
<input type="reset" value="Reset"/>
</p>
<p style="color:red" id="ErrorMessage"> </p>
</form>
</body>
</html>
You cannot see the error messages because the form submission refreshes the page. To see the errors, use event.preventDefault to get the errors.
Try the below code.
<html lang="en">
<head>
<title> Lab 6 - Task 2 </title>
<style>
span {
padding-left: 10px;
display: block;
float: left;
width: 20%;
}
button { margin-left: 10px; }
body {
width: 80%; margin: auto; font-family: sans-serif;
border: 1px solid black;
}
</style>
<meta charset="utf-8">
</head>
<body>
<form id="myForm" method="get">
<h1> Form Submit </h1>
<p> <span>Name:</span> <input type="text" id="input1" placeholder="Enter Name" name="Name" onfocus="clearMyField(this);"></p>
<p> <span>Student Id:</span> <input type="text" id="input2" placeholder="Enter Student ID" name="StudentID" onfocus="clearMyField(this);"></p>
<p> <span>Email:</span> <input type="text" id="input3" placeholder="Enter Email" name="Email" onfocus="clearMyField(this);"></p>
<p>
<button id="submitButton" type="submit"> Submit </button>
<input type="reset" value="Reset">
</p>
<p style="color:red" id="ErrorMessage"> </p>
</form>
<script>
var message = document.getElementById("ErrorMessage");
//document.getElementById('myForm')
function clearMyField(el) {
if (el.placeholder != '') {
el.placeholder = '';
}
}
//Add event listener
document.getElementById('myForm')
.addEventListener('submit', function (e) {
console.log('submit')
//prevent the default submission to see the errors.
e.preventDefault()
var allInputs = document.querySelectorAll('input[type=text]');
for (let i = 0; i < allInputs.length; i++) {
let v = allInputs[i].value.trim();
let n = allInputs[i].name;
if (v == "") {
message.textContent = n + " is empty";
return false;
}
}
})
</script>
</body>
</html>
I have a contact form that when you press the send button, opens a popup asking for confirmation of reading the privacy policy.
For now, the form doesn't send anything if there are empty required field, but it opens the popup.
I need to prevent the popup to open if there are still required field to complete.
Here's the code:
$('#myCheck').click(function() {
$(this).toggleClass("checked");
});
(function($) {
$.fn.toggleDisabled = function(){
return this.each(function(){
this.disabled = !this.disabled;
});
};
})(jQuery);
$('.checkz').click(function () {
$('#invias').toggleDisabled();
$('#invias').toggleClass("activ3");
});
$(".pex").click(function (e) {
e.stopPropagation();
});
function checkInputs() {
var isValid = true;
$('input').filter('[required]').each(function() {
if ($(this).val() === '') {
$('#confirm').prop('disabled', true)
isValid = false;
return false;
}
});
if(isValid) {$('#confirm').prop('disabled', false)}
return isValid;
}
//Enable or disable button based on if inputs are filled or not
$('input').filter('[required]').on('keyup',function() {
checkInputs()
})
checkInputs()
.checkz {width:20px;
height:20px;
background: transparent;
background-size: contain;
border:1px solid #CCC;
border-radius:5px;
display:inline-block;
margin-bottom: 5px;
margin-right: 10px;}
#invias {opacity:0.5}
.activ3 {opacity:1 !important}
#popup {
background-color: rgba( 231, 135, 74, 0.85 );
position: fixed;
height: 100%;
width: 100%;
top: 0;
left: 0;
right: 0;
bottom: 0;
z-index: 1999999999;
overflow: initial;
transition: all .15s ease-in-out;
}
.pex {width:500px;padding:30px;background:#FFF;z-index:1999999999;margin: 10% auto 0;text-align: center;}
.cst {display: inline-block;
text-align: left;}
.checked {background-image: url(https://image.flaticon.com/icons/png/512/3/3596.png)}
button:disabled {opacity:0.5 !important}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script>
function popupshow() {
document.getElementById("popup").style = "";
}
function popupban() {
document.getElementById("popup").style.display = "none";
}
</script>
<form method="post" name="contactform" class="peThemeContactForm">
<div class="col-md-5 col-sm-5 col-xs-12 animated hiding" data-animation="slideInLeft">
<div class="form-group">
<input type="text" name="author" class="form-control input-lg" placeholder="Name*" required />
</div>
<div class="form-group">
<input type="email" name="email" class="form-control input-lg" placeholder="Email*" required />
</div>
<div class="form-group">
<input type="text" name="phone" class="form-control input-lg" placeholder="Phone">
</div>
</div>
<div class="col-md-7 col-sm-7 col-xs-12 animated hiding" data-animation="slideInRight">
<div class="form-group">
<textarea name="message" class="form-control input-lg" placeholder="Message*" required ></textarea>
</div>
</div>
<a onclick="popupshow()" class="btn btn-custom up animated hiding" data-animation="fadeInUpBig" id="confirm">Send message</a>
<div id="popup" style="display:none;">
<div class="pex">
<div class="checkz" id="myCheck"></div> <div class="cst">Dichiaro di aver letto, compreso ed accettato
<br>l'informativa sul trattamento dei miei dati personali</div>
<br><br><a class="btn btn-custom" onclick="popupban()" >Close</a> <button type="submit" class="btn btn-custom" id="invias" onclick="popupban()" disabled>Accept</button>
</div>
</div>
You could use the following fiddle to test: http://jsfiddle.net/2BgdD/12/
Thanks a lot.
If you set isValid as a global variable, you can use it to do a check before firing your popupshow method:
function popupshow() {
if (!isValid) return;
document.getElementById("popup").style = "";
}
You would need to adjust your checkInputs method as well though:
function checkInputs() {
$('input').filter('[required]').each(function() {
if ($(this).val() === '') {
$('#confirm').prop('disabled', true)
isValid = false;
} else {
isValid = true;
}
});
if(isValid) {$('#confirm').prop('disabled', false)}
return isValid;
}
Updated Demo
function popupshow() {
if(checkInputs()) document.getElementById("popup").style = "";
}
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');.
I need to create tabs in a reservation form (3 tabs) that contain text boxes for the user to fill out then submit. I can't seem to get it to work though and I'm not sure why? Did I place the content (the text boxes) in the wrong place?
$(document).ready(function() {
//tabs function
$("#reservation_tabs").tabs();
var emailPattern = /\b[A-Za-z0-9._%+-]+#[A-Za-z0-9.-]+\.[A-Za-z]{2,4}\b/;
// add a span element after each text box
$(":text").after("<span class='error'>*</span>");
// move the focus to the first text box
$("#arrival_date").focus();
// 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
if ($("#arrival_date").val() == "") {
$("#arrival_date").next().text("This field is required.");
isValid = false;
} else {
$("#arrival_date").next().text("");
}
// validate the number of nights
if ($("#nights").val() == "") {
$("#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("");
}
// 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("");
}
// 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("");
}
// validate the phone number
if ($("#phone").val() == "") {
$("#phone").next().text("This field is required.");
isValid = false;
} else {
$("#phone").next().text("");
}
// 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%;
}
.error {
float: none;
color: red;
font-size: 85%;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Reservation request</title>
<link rel="stylesheet" href="main.css">
<script src="http://code.jquery.com/jquery-2.1.4.min.js"></script>
<script src="reservation.js"></script>
</head>
<body>
<h1>Reservation Request</h1>
<form action="response.html" method="get"
name="reservation_form" id="reservation_form">
<div id="reservation_tabs">
<ul>
<li>General Information</li>
<li>Preferences</li>
<li>Contact Information</li>
</ul>
<div id="general_information">
<label for="arrival_date">Arrival date:</label>
<input type="text" name="arrival_date" id="arrival_date" autofocus><br>
<label for="nights">Nights:</label>
<input type="text" name="nights" id="nights"><br>
<label>Adults:</label>
<select name="adults" id="adults">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
</select><br>
<label>Children:</label>
<select name="children" id="children">
<option value="0">0</option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
</select><br>
</div>
<div id="preferences">
<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>
<div id="contact_information">
<label for="name">Name:</label>
<input type="text" name="name" id="name"><br>
<label for="email">Email:</label>
<input type="text" name="email" id="email"><br>
<label for="phone">Phone:</label>
<input type="text" name="phone" id="phone" placeholder="999-999-9999"><br>
</div>
</div>
<fieldset>
<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>
</fieldset>
</form>
</body>
</html>
Tabs are part of the jQuery UI https://jqueryui.com/tabs/ lib (it's different file than the jQuery itself, so you need them both) which you haven't referenced. (cdns here)
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?