Html input checkbox over javascript function - javascript

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 :)

Related

How do I make the second div have the same height as first div, irrespective of the screen-width?

I want my two divs to be of equal height regardless of the device used to view the page. To ensure this, I wrote the js function below:
window.onload = function() {
var left=document.getElementsByClassName('bg-text')[0].clientHeight;
var right=document.getElementsByClassName('para')[0].clientHeight;
if(left>right) {
document.getElementsByClassName('para')[0].style.height=left+"px";
}
else{
document.getElementsByClassName('bg-text')[0].style.height=right+"px";
}
};
The code above works for most cases, not all. As I keep on reducing the screen width from the console, the second div becomes larger than the first div. How do I fix this?
**EDIT: ** This is my html:
<div class="bg-text">
<h4><u>Newspaper particulars</u></h4><br>
<ul>
<li><label for="date">Select date :</label><br></li>
<input type="date" id="date" name="date" style="text-align: center; width: 100%;"><br><br>
<li><label for="news">Select newspaper :</label><br></li>
<select name="news" id="news" style="text-align: center; width: 100%;">
<option value="default">Click to select</option>
<option value="The Assam Tribune">The Assam Tribune</option>
<option value="The Times of India">The Times of India</option>
<option value="The Hindu">The Hindu</option>
<option value="Hindustan Times">Hindustan Times</option>
<option value="The Telegraph">The Telegraph</option>
</select><br><br>
<li><label for="paragraph_text" id="para">Subject description :</label><br></li>
<textarea name="paragraph_text" id="paragraph_text" rows="3" style="resize: none; box-sizing:border-box; width: 100%; -webkit-box-sizing: border-box; -moz-box-sizing: border-box;"></textarea><br><br>
<span>Choose the required mode of input</span>
<li><div class="mb-3" style="width: 100%; border: 2px solid white; padding: 10px;">
<input type="radio" id="sel_scan" name="doc" value="scanning">
<button id="scan" onclick="startScan()" disabled>Scan document</button><br><br>
<div style="width: 100%;">
<input type="radio" id="myfile" name="doc" value="choosing">
<input type="file" id="Myfile" accept=".pdf,.jpg,.png" disabled>
</div>
</div></li>
</ul>
</div>
<div class="para">
<div class="container">
<span id="preview_text" style="text-align: center; vertical-align: middle; line-height: 400px; color: red;">Choose/Scan file to see preview here</span>
</div>
</div>
I want both the divs bg-text and para be of equal heights. Infact, as the second div is empty, so I want it to be the same height as that of the first div
You need to adjust the heights on resize as well. The code below should work:
function setHeight() {
var leftElement = document.getElementsByClassName('bg-text')[0];
var rightElement = document.getElementsByClassName('para')[0];
// Reset height
leftElement.style.height = "auto";
rightElement.style.height = "auto";
var leftHeight = leftElement.offsetHeight;
var rightHeight = rightElement.offsetHeight;
// Get max height and set it for both divs
var maxHeight = Math.max(leftHeight, rightHeight);
leftElement.style.height = maxHeight+"px";
rightElement.style.height = maxHeight+"px";
}
window.onload = function() {
setHeight();
};
window.onresize = function() {
setHeight();
}

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');.

Tabs won't work in jQuery?

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)

JQuery won't change HTML of an id

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

How to get value the input type without value attribute

i got stuck with this. I have HTML file like this:
$(document).ready(function() {
$('select.supplier').change(function() {
var capacityValue = $('select.supplier').find(':selected').data('capacity');
$('.supplierCapacity').val(capacityValue);
});
});
$(document).ready(function() {
$('select.supplier').change(function() {
var countryValue = $('select.supplier').find(':selected').data('country');
$('.supplierCountry').val(countryValue);
});
});
select,
input {
padding: 5px;
margin: 5px 0 10px;
font-weight: bold;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Choose Supplier :
<br>
<form method="post" action="submit.php">
<select class="supplier" name="supplier">
<option data-country="Argentine" data-capacity="100" value="10">Johny Farms</option>
<option data-country="Belgium" data-capacity="200" value="20>">Jack & Jane Farms</option>
<option data-country="Canada" data-capacity="300" value="30">Crabs Crane</option>
</select><br>
<input type="hidden" name="supplierCapacity" class="supplierCapacity" readonly /><br>
Country :<br>
<input type="text" name="supplierCountry" class="supplierCountry" readonly /><br>
<input type="submit" value=" save ">
</form>
How do get the input value to post. I wrote this code in submit.php but doesn't work:
$capacity = $_POST['supplierCapacity'];
$country = $_POST['supplierCountry'];
Put a id for the input
<input id="testing" />
In javascript, to get the input value
document.getElementId('testing').value
Or
$('#testing').val();

Categories

Resources