Tabs won't work in jQuery? - javascript

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)

Related

How to hide the check boxes dropdown by clicking outside the dropdown [duplicate]

This question already has answers here:
How do I detect a click outside an element?
(91 answers)
Closed 3 years ago.
I had created a sample check boxes dropdown, I facing an issue in hiding the dropdown by clicking outside the dropdwon. Below is the code
var expanded = false;
function showCheckboxes() {
var checkboxes = document.getElementById("checkboxes");
if (!expanded) {
checkboxes.style.display = "block";
expanded = true;
} else {
checkboxes.style.display = "none";
expanded = false;
}
}
$('#checkboxes').click(function(e) {
e.stopPropagation();
});
$(document).click(function() {
$('#checkboxes').style.display = "none";
});
.category {
width: 250px;
}
#checkboxes {
width: 250px;
display: none;
border: 1px #aaa solid;
overflow-y: scroll;
background-color: white;
}
#checkboxes label {
display: block;
}
#checkboxes label:hover {
background-color: #bbb;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select class="category" onclick="showCheckboxes()">
<option value="">Select cities
</option>
</select>
<div id="checkboxes">
<label>
<input type="checkbox" /> Bangalore
</label>
<label>
<input type="checkbox" /> Hyderabad
</label>
<label>
<input type="checkbox" /> Delhi
</label>
<label>
<input type="checkbox" /> Mumbai
</label>
<label>
<input type="checkbox" /> Chennai
</label>
<label>
<input type="checkbox" /> Panaji
</label>
</div>
I want the drop down to get close by clicking outside any where. kindly help me on this i tried the script to make the display style none, but its not working
style is a property on HTMLElement, it is not available on jQuery. You should use .css() on jQuery object:
Change
$('#checkboxes').style.display = "none";
To
$('#checkboxes').css("display","none");
Though I prefer using show()/hide() instead of setting the style property.
You can check the event.target.nodeName to show()/hide() the element.
Try the following way:
function showCheckboxes() {
if ($('#checkboxes').is(':visible')) {
$('#checkboxes').hide();
}
else {
$('#checkboxes').show();
}
}
$(document).click(function(e) {
if(e.target.nodeName == 'BODY')
$('#checkboxes').hide();
});
.category {
width: 250px;
}
#checkboxes {
width: 250px;
display: none;
border: 1px #aaa solid;
overflow-y: scroll;
background-color: white;
}
#checkboxes label {
display: block;
}
#checkboxes label:hover {
background-color: #bbb;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select class="category" onclick="showCheckboxes()">
<option value="">Select cities
</option>
</select>
<div id="checkboxes">
<label >
<input type="checkbox" /> Bangalore
</label>
<label>
<input type="checkbox" /> Hyderabad
</label>
<label>
<input type="checkbox" /> Delhi
</label>
<label>
<input type="checkbox" /> Mumbai
</label>
<label>
<input type="checkbox" /> Chennai
</label>
<label>
<input type="checkbox" /> Panaji
</label>
</div>
Alternatively you can try multi Select dropDownList with check Boxes using jQuery plugin as explain here MultiSelect DropDownList With CheckBoxes In ASP.Net With C# And VB.NET Using jQuery Plugin

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 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?

Html input checkbox over javascript function

I have created a simple payment form using HTML/CSS/JS and i want to make checks of what the user gives as inputs using html patterns. But i also want to create a pop up alert using JS to confirm the form which must pop after all required inputs are filled correctly and patterns are ok.The pop up alert must also contain the name the user provided and return it.But the problem is that when i press submit button, even though the required info is not filled, the alert does come up and says "Order Completed" ....How can i make the pop up come up only after all info is given correctly?Here is my code:
<!DOCTYPE html>
<html>
<style>
body {
border:10px solid black;
margin-top: 100px;
margin-bottom: 100px;
margin-right: 150px;
margin-left: 150px;
}
p.thick {
font-weight: bold;
}
input[type=text], select {
width: 100%;
padding: 20px 20px;
margin: 8px 0;
display: inline-block;
border: 1px solid #ccc;
border-radius: 4px;
box-sizing: border-box;
}
input[type=text]:focus {
border: 3px solid #555;
}
input[type=password]:focus {
border: 3px solid #555;
}
input[type=password], select {
width: 100%;
padding: 20px 20px;
margin: 8px 0;
display: inline-block;
border: 1px solid #ccc;
border-radius: 4px;
box-sizing: border-box;
}
input[type=submit] {
width: 100%;
background-color: #4CAF50;
color: white;
padding: 14px 20px;
margin: 8px 0;
border: none;
border-radius: 4px;
cursor: pointer;
}
input[type=submit]:hover {
background-color: red;
}
div {
border-radius: 5px;
background-color:rgb(238, 238, 232);
padding: 40px;
}
</style>
<body onload="CreditCard();">
<form id="Myform">
<div class="login-page">
<div class="form">
<fieldset>
<h1>Log in </h1>
<p>Username*: <input type="text" name="Username" pattern=".{3,}" title="3 or more characters"></p>
<p>Password*: <input type="password" name="pw" pattern="(?=.*\d)(?=.*[A-Z]).{5,}"placeholder="Password must contain 1 uppercaser and 1 number and must be atleast 5 digits." title="Must contain at least one number and one uppercase letter, and at least 5 or more characters."></p>
</fieldset>
<fieldset>
<h1> Payment </h1>
<select id="paymentmethod" onchange="CreditCard();">
<option value ="Payment on pickup">Payment on pickup</option>
<option value="Bank transfer/deposit">Bank transfer/deposit</option>
<option value="Credit/Debit card">Credit/Debit card</option>
</select>
<fieldset>
<div id="credit/debit card" style="display: block;">
<select name="cardtype" class="form">
<option value="VISA">VISA</option>
<option value="MasterCard">MasterCard</option>
</select>
<br>Card Number*:<br>
<input type="text" name="cardnumber" pattern="(?=.*\d).{16,16}" title="Enter a 16-digit card number please." style="width:80%;" maxlength="20" value="" required>
<tr>
<td height="22" align="right" valign="middle">Expiry Date:</td>
<td colspan="2" align="left">
<SELECT NAME="CCExpiresMonth" >
<OPTION VALUE="01">January (01)
<OPTION VALUE="02">February (02)
<OPTION VALUE="03">March (03)
<OPTION VALUE="04"SELECTED>April (04)
<OPTION VALUE="05">May (05)
<OPTION VALUE="06">June (06)
<OPTION VALUE="07">July (07)
<OPTION VALUE="08">August (08)
<OPTION VALUE="09">September (09)
<OPTION VALUE="10">October (10)
<OPTION VALUE="11">November (11)
<OPTION VALUE="12">December (12)
</SELECT>
<SELECT NAME="CardExpiresYear">
<OPTION VALUE="04"SELECTED>2016
<OPTION VALUE="05">2017
<OPTION VALUE="06">2018
<OPTION VALUE="07">2019
<OPTION VALUE="08">2020
<OPTION VALUE="09">2021
<OPTION VALUE="10">2022
<OPTION VALUE="11">2023
<OPTION VALUE="12">2024
<OPTION VALUE="13">2025
</SELECT>
</td>
</tr>
</fieldset>
</fieldset>
<h1> Order Information </h1>
<p class="thick"> Name*: </p> <input type="text" id="customername" style="width:55% name="cardholder" value="" pattern=".{1,}" title="Please enter a name" required>
<p class="thick"> Adress*: </p> <input type="text"style="width:55;" name="cardholderadr" value="" pattern=".{3,}" title="Please enter an adress" required>
<p class="thick"> Phone </p> <input type="text"style="width:55;" pattern="(?=.*\d).{10,10}" title="Enter a 10 digit number please." name="cardholderpho" value="" >
<p class="thick"> email <input type="text" name="email" pattern="[a-z0-9._%+-]+#[a-z0-9.-]+\.[a-z]{2,3}$" title="Please enter a valid email adress" placeholder="example#email.com" >
<p class="thick"> Delivery comments </p> <input type="text" style="width:55; padding: 50px ;" name="cardholdercomm" value="" >
<p style="color:blue;"> I agree with the <a href="https://en.wikipedia.org/wiki/Terms_of_service">
*terms</a> <input type="radio" name="terms" title="Please agree to our terms." unchecked required onclick="terms();"></p>
<input type="submit" value="Submit" onclick="confirmed();">
<input type="button" onclick="reset()" value="Reset form">
</div>
</div>
</form>
<script>
function CreditCard() {
prefer = document.forms[0].paymentmethod.value;
if (prefer == "Credit/Debit card") {
document.getElementById("credit/debit card").style.visibility = "visible";
} else {
document.getElementById("credit/debit card").style.visibility = "hidden";
}
}
function paymentwithcard() {
document.getElementById("credit/debit card").style.visibility = "hidden";
}
function reset() {
document.getElementById("Myform").reset();
}
function confirmed() {
var x = document.getElementById("customername").value;
alert("Order completed.Name used:" + x);
}
function terms() {
}
</script>
</body>
</html>
Focus on the inputs and the function confirmed().
The submit method executes when you press submit.
First you have to let the submit method wait that the comfirm method can execute, after it the submit method can be executed.
To accessing the attribute in your js you can use an id.
document.getElementById('submit-form').submit(function(ev) {
ev.preventDefault(); // to stop the form from submitting
confirmed();
this.submit(); // If confirmed succeeded
});
<input id="submit-form" type="submit" value="Submit">
To prevent form from submitting you need to change `onclick attribute
<input type="submit" value="Submit" onclick="return confirmed();">
and your function must return true or false depending on your form validation.
You are listening onclick, instead, you should listen for the submit event
Don't only rely on client-side validation, it's good for a clean UX but never trust the client
HTML5 provides some validation options in the form of the required and pattern attributes
window.addEventListener('load', function () {
document.getElementById('example-submit').addEventListener('submit', function () {
alert('done');
});
});
input:invalid {border: 1px solid red;}
input:valid {border: 1px solid green;}
<form action="?" method="post">
<input type="text" id="expire-year" required pattern="20[123]\d" placeholder="YYYY" />
<input type="text" id="expire-month" required pattern="0?[1-9]|1[012]" placeholder="MM" />
<input type="text" id="expire-day" required pattern="0?[1-9]|2\d|3[01]" placeholder="DD" />
<input type="submit" id="example-submit" />
</form>
Side notes
In your code, CreditCard isn't a constructor. Consider using a cammel case name creditCard instead
Try to cut down the code in your question to the bare minimum/example case if you want good quality answers, nearly all of the HTML provided is irrelevant to the question
I didn't use a snippet because the embedded iframe here on SO doesn't let you submit forms :)

Categories

Resources