I have a code like this and cannot validate the checkbox field while it is checked. Can you help me please? I mean only the #check id in checkbox input field. Something doesn't work me.
Email works correctly, name also, but the checkbox I don't know how to validate it to have it checked by user. If not it should give us information "Accept policy".
$(function() {
var form = document.querySelector("#form");
form.addEventListener("submit", function(e) {
e.preventDefault();
var valid;
valid = validateContact();
if (valid) {
jQuery.ajax({
url: "contact-form.php",
data: '&name=' + $("#name").val() +
'&email=' + $("#email").val() +
'&address=' + $("#address").val() +
'&check=' + $("#check").val() +
'&message=' + $("#message").val(),
type: "POST",
success: function() {
document.getElementById("form").reset();
$('#contact-after-msg').text('Dziękujemy za złożenie zamówienia. Odezwiemy się do Państwa jeszcze dziś.');
},
error: function() {
alert('Coś poszło nie tak, spróbuj ponownie');
}
});
}
function validateContact() {
var valid = true;
if (!$("#name").val()) {
$("#name").css("border", "solid 1px #ff5d5d");
$("#name-info").html("Podaj imię i nazwisko");
valid = false;
} else {
$("#name").css("border", "none");
$("#name-info").html("");
}
if (!$("#address").val()) {
$("#address").css("border", "solid 1px #ff5d5d");
$("#address-info").html("Podaj adres wysyłki");
valid = false;
} else {
$("#address").css("border", "none");
$("#address-info").html("");
}
if (!$("#email").val()) {
$("#email").css("border", "solid 1px #ff5d5d");
$("#email-info").html("Podaj adres e-mail");
valid = false;
} else if (!$("#email").val().match(/^([\w-\.]+#([\w-]+\.)+[\w-]{2,4})?$/)) {
$("#email").css("border", "solid 1px #ff5d5d");
$("#email-info").html("Adres e-mail jest niepoprawny");
valid = false;
} else {
$("#email").css("border", "none");
$("#email-info").html("");
}
if (!$("#check").val().checked === true) {
$("#check").css("border", "solid 1px #ff5d5d");
$("#check-info").html("Accept Policy");
valid = false;
} else {
$("#check").css("border", "none");
$("#check-info").html("");
}
return valid;
}
});
});
<form class="t-contact-form__form" id="form" novalidate>
<div class="t-contact-form__item">
<span id="name-info"></span>
<input class="t-contact-form__field" name="name" placeholder="Imię i nazwisko" type="text" id="name" required>
</div>
<div class="t-contact-form__item">
<span id="email-info"></span>
<input class="t-contact-form__field" name="email" placeholder="Adres email" type="email" id="email" required>
</div>
<div class="t-contact-form__item">
<span id="address-info"></span>
<input class="t-contact-form__field" name="address" placeholder="Adres" type="text" id="address" required>
</div>
<div class="t-contact-form__item">
<textarea class="t-contact-form__field" name="message" placeholder="Masz dodatkowe życzenia? Zamawiasz więcej egzemplarzy?" required id="message"></textarea>
<div class="t-contact-form__item">
<span id="check-info"></span>
<h5><input class="t-contact-form__field u-mt-2" name="check" type="checkbox" id="check" required>I accept the terms.
</h5>
</div>
<div class="t-contact-form__button">
<button class="c-btn c-button c-button--contact-send" name="submit" type="submit" id="contact-submit">Buy</button>
<div class="t-contact-form__policy-buttons">
<a class="c-btn" href="images/REGULAMIN ZAMÓWIENI.pdf">Policy
<a class="c-btn" href="images/POLITYKA PRYWATNOŚCI.pdf">Terms
</div>
</div>
<div class="contact-msg-success" id="contact-after-msg"></div>
</div>
</form>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
</head>
<form class="t-contact-form__form" id="form" novalidate>
<div class="t-contact-form__item">
<span id="name-info"></span>
<input class="t-contact-form__field" name="name" placeholder="Imię i nazwisko" type="text" id="name" required>
</div>
<div class="t-contact-form__item">
<span id="email-info"></span>
<input class="t-contact-form__field" name="email" placeholder="Adres email" type="email" id="email" required>
</div>
<div class="t-contact-form__item">
<span id="address-info"></span>
<input class="t-contact-form__field" name="address" placeholder="Adres" type="text" id="address" required>
</div>
<div class="t-contact-form__item">
<textarea class="t-contact-form__field" name="message" placeholder="Masz dodatkowe życzenia? Zamawiasz więcej egzemplarzy?" required id="message"></textarea>
<div class="t-contact-form__item">
<span id="check-info"></span>
<h5><input class="t-contact-form__field u-mt-2" name="check" type="checkbox" id="check" required>I accept the terms.
</h5>
</div>
<div class="t-contact-form__button">
<button class="c-btn c-button c-button--contact-send" name="submit" type="submit" id="contact-submit">Buy</button>
<div class="t-contact-form__policy-buttons">
<a class="c-btn" href="images/REGULAMIN ZAMÓWIENI.pdf">Policy
<a class="c-btn" href="images/POLITYKA PRYWATNOŚCI.pdf">Terms
</div>
</div>
<div class="contact-msg-success" id="contact-after-msg"></div>
</div>
</form>
<script>
$(function() {
var form = document.querySelector("#form");
form.addEventListener("submit", function(e) {
e.preventDefault();
var valid;
valid = validateContact();
if (valid) {
jQuery.ajax({
url: "contact-form.php",
data: '&name=' + $("#name").val() +
'&email=' + $("#email").val() +
'&address=' + $("#address").val() +
'&check=' + $("#check").val() +
'&message=' + $("#message").val(),
type: "POST",
success: function() {
document.getElementById("form").reset();
$('#contact-after-msg').text('Dziękujemy za złożenie zamówienia. Odezwiemy się do Państwa jeszcze dziś.');
},
error: function() {
alert('Coś poszło nie tak, spróbuj ponownie');
}
});
}
function validateContact() {
var valid = true;
if (!$("#name").val()) {
$("#name").css("border", "solid 1px #ff5d5d");
$("#name-info").html("Podaj imię i nazwisko");
valid = false;
} else {
$("#name").css("border", "none");
$("#name-info").html("");
}
if (!$("#address").val()) {
$("#address").css("border", "solid 1px #ff5d5d");
$("#address-info").html("Podaj adres wysyłki");
valid = false;
} else {
$("#address").css("border", "none");
$("#address-info").html("");
}
if (!$("#email").val()) {
$("#email").css("border", "solid 1px #ff5d5d");
$("#email-info").html("Podaj adres e-mail");
valid = false;
} else if (!$("#email").val().match(/^([\w-\.]+#([\w-]+\.)+[\w-]{2,4})?$/)) {
$("#email").css("border", "solid 1px #ff5d5d");
$("#email-info").html("Adres e-mail jest niepoprawny");
valid = false;
} else {
$("#email").css("border", "none");
$("#email-info").html("");
}
if (!$('#check').is(':checked')) {
$("#check").css("border", "solid 1px #ff5d5d");
$("#check-info").html("Accept Policy");
valid = false;
} else {
$("#check").css("border", "none");
$("#check-info").html("");
}
return valid;
}
});
});
</script>
if (!$('#check').is(':checked')) { This line validate checkbox selected or not. Hope it helps.
Related
So I want to check if both the email input and password input are filled before allowing the submit button to be pressed. I keep getting back that the variables stay false.
My Javscript:
var filled1 = false;
var filled2 = false;
setInterval(function() {
if ($(".login_email").length > 2) {
filled1 = true;
} else {
filled1 = false;
}
if($(".login_pass").length > 2) {
filled2 = true;
} else {
filled2 = false;
}
if(filled1 == true && filled2 == true) {
$(".login_sub").css("cursor", "pointer");
$(".login_sub").css("opacity", "1");
$(".login_sub").attr("onclick", "document.forms['login_form'].submit();");
} else {
$(".login_sub").css("cursor", "not-allowed");
$(".login_sub").css("opacity", "0.6");
$(".login_sub").attr("onclick", "");
}
}, 500);
and Form :
<form method="POST" name="login_form">
<input type="email" name="login_email" class="login_email" placeholder="Email"/>
<br/>
<input type="password" name="login_pass" class="login_pass" placeholder="Password"/>
<br/>
<div class="login_sub" name="sub_login">Login</div>
</form>
You have some extra code. Simply check the value length of the fields:
setInterval(function() {
if($(".login_email").val().length && $(".login_pass").val().length) {
$(".login_sub").css("cursor", "pointer");
$(".login_sub").css("opacity", "1");
$(".login_sub").attr("onclick", "document.forms['login_form'].submit();");
} else {
$(".login_sub").css("cursor", "not-allowed");
$(".login_sub").css("opacity", "0.6");
$(".login_sub").attr("onclick", "");
}
}, 500);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form method="POST" name="login_form">
<input type="email" name="login_email" class="login_email" placeholder="Email"/>
<br/>
<input type="password" name="login_pass" class="login_pass" placeholder="Password"/>
<br/>
<div class="login_sub" name="sub_login">Login</div>
</form>
Though I personally prefer the following approach (without setInterval()):
$(".login_sub").css("cursor", "not-allowed");
$(".login_sub").css("opacity", "0.6");
function submitForm() {
if($(".login_email").val().length && $(".login_pass").val().length) {
$(".login_sub").css("cursor", "pointer");
$(".login_sub").css("opacity", "1");
$(".login_sub").attr("onclick", "document.forms['login_form'].submit();");
} else {
$(".login_sub").css("cursor", "not-allowed");
$(".login_sub").css("opacity", "0.6");
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form method="POST" name="login_form">
<input type="email" oninput="submitForm()" name="login_email" class="login_email" placeholder="Email"/>
<br/>
<input type="password" oninput="submitForm()" name="login_pass" class="login_pass" placeholder="Password"/>
<br/>
<div class="login_sub" name="sub_login">Login</div>
</form>
You can use the required attribute and checkValidity() method. Also you need a button to submit a form. There is no need of setInterval here
let email = document.getElementById('login_email');
let password = document.getElementById('login_pass');
// on keyup from the input check if the field is empty, then disable the
// submit button
$('.nt-empty').on('keyup', function() {
if (email.checkValidity() && password.checkValidity()) {
$('.login_sub').attr('disabled', false)
} else {
$('.login_sub').attr('disabled', true)
}
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form method="POST" name="login_form">
<input type="email" name="login_email" id="login_email" class="login_email nt-empty" placeholder="Email" required />
<br/>
<input type="password" name="login_pass" id="login_pass" class="login_pass nt-empty" placeholder="Password" required />
<br/>
<button disabled class="login_sub" name="sub_login" type="submit">Login</button>
</form>
After clicking submit the form is not producing errors next to the input fields ,it refreshes the page and clears all the fields.
HTML:
<form id="mc-form" method="POST">
<div class="form-group col-xs-12 ">
<label for="name" hidden>שם פרטי</label>
<input type="text" name="name" id="name" class="cv form-control" placeholder="שם פרטי" onkeyup='validateMessage()'>
<span class='error-message' id='name-error'></span>
</div>
<div class="form-group col-xs-12 ">
<label for="lastName" hidden>שם משפחה</label>
<input type="text" name="lastName" id="lastName" class="cv form-control" placeholder="שם משפחה" onkeyup='validateMessage()'>
<span class='error-message' id='name-error'></span>
</div>
<div class="form-group col-xs-12 ">
<label for="phone" hidden>טלפון</label>
<input type="text" name="phone" id="phone" class="cv form-control" placeholder="טלפון" onkeyup='validateMessage()'>
<span class='error-message' id='name-error'></span>
</div>
<div class="form-group col-xs-12 ">
<label for="email" hidden>דואר אלקטרוני</label>
<input type="email" name="email" id="email" class="cv form-control" placeholder="דואר אלקטרוני" onkeyup='validateMessage()'>
<span class='error-message' id='name-error'></span>
</div>
<div class="form-group col-xs-12 ">
<label for="subject" hidden>נושא</label>
<input type="text" name="subject" id="subject" class="cv form-control" placeholder="נושא" onkeyup='validateMessage()'>
</div>
<div class="form-group col-xs-12 ">
<label for="message" hidden>הודעה</label>
<textarea name="message" id="message" class="cv form-control message" placeholder="השאירו את הודעתכם פה" rows="4" cols="50" onkeyup='validateMessage()'></textarea>
</div>
<!-- <input type="submit" id="submit-button" class="btn btn-custom-outline " value="שלח" > -->
<button onclick='return validateForm()' class="btn btn-custom-outline " id="submit-button">שלח</button>
<span class='error-message' id='submit-error'></span>
<br>
<!-- <div class="success"><?= $success ?></div>-->
<!--<span class="error"></span> -->
</form>
My JavaScript:
function validateName() {
var name = document.getElementById('name').value;
if(name.length == 0) {
producePrompt('Name is required', 'name-error' , 'red')
return false;
}
if (!name.match( /^[a-zא-ת]+(\s[a-zא-ת]+)*$/i)) {
producePrompt('Letters only please.','name-error', 'red');
return false;
}
producePrompt('Valid', 'name-error', 'green');
return true;
}
function validatePhone() {
var phone = document.getElementById('phone').value;
if(phone.length == 0) {
producePrompt('Phone number is required.', 'phone-error', 'red');
return false;
}
if(!phone.match(/^[0-9]{10}$/)) {
producePrompt('Only digits, please.' ,'phone-error', 'red');
return false;
}
producePrompt('Valid', 'phone-error', 'green');
return true;
}
function validateEmail () {
var email = document.getElementById('email').value;
if(email.length == 0) {
producePrompt('Email Invalid','email-error', 'red');
return false;
}
if(!email.match(/^[A-Za-z\._\-[0-9]*[#][A-Za-z]*[\.][a-z]{2,4}$/)) {
producePrompt('Email Invalid', 'email-error', 'red');
return false;
}
producePrompt('Valid', 'email-error', 'green');
return true;
}
/*function validateMessage() {
var message = document.getElementById('contact-message').value;
var required = 30;
var left = required - message.length;
if (left > 0) {
producePrompt(left + ' more characters required','message-error','red');
return false;
}
producePrompt('Valid', 'message-error', 'green');
return true;
}*/
function validateForm() {
if (!validateName() || !validatePhone() || !validateEmail() ) {
jsShow('submit-error');
producePrompt('Please fix errors to submit.', 'submit-error', 'red');
setTimeout(function(){jsHide('submit-error');}, 2000);
return false;
}
else {
}
}
function jsShow(id) {
document.getElementById(id).style.display = 'block';
}
function jsHide(id) {
document.getElementById(id).style.display = 'none';
}
function producePrompt(message, promptLocation, color) {
document.getElementById(promptLocation).innerHTML = message;
document.getElementById(promptLocation).style.color = color;
}
My scrips are in index.html , same page the form is, in the end :
<script src="https://code.jquery.com/jquery-3.2.1.slim.min.js" ></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.3/umd/popper.min.js" ></script>
<script src="js/bootstrap.min.js" ></script>
<!-- [ SLIDER SCRIPT ] -->
<script type="text/javascript" src="js/SmoothScroll.js"></script>
<script src="js/script.js" ></script>
<script src="js/validateform.js" ></script>
After clicking submit the form is not producing errors next to the input fields ,it refreshes the page and clears all the fields.
The issue that you are running into in calling
producePrompt('Email Invalid','email-error', 'red');
and any other where you are not passing name-error an error is occurring as there is no element with the id email-error they all have the same id. When the error is thrown the function returns undefined instead of false causing the form to be submitted.
When using Chrome dev tools you can go into settings and check preserve log this will allow you to see errors even after the page refreshes.
As to checking for all errors instead of just the first one...
the if (!validateName() || !validatePhone() || !validateEmail() ) {
or statements here mean the first one that false causes the rest to not be checked. Instead you could do something like the following
var vn = validateName();
var vp = validatePhone();
var ve = validateEmail();
if (!vn || !vp || !ve) {
**Below is the code for basic user registration form but it is not validating the form... Please can anyone tell me where is the problem. Except validation remaining code is working. Please tell me what to do for it*
function validateForm()
{
var fName = document.forms["myForm"]["fName"].value;
var lName = document.forms["myForm"]["lName"].value;
var email = document.forms["myForm"]["email"].value;
var username = document.forms["myForm"]["username"].value;
var pwd = document.forms["myForm"]["pwd"].value;
var password = document.forms["myForm"]["password"].value;
var mobile = document.forms["myForm"]["mobile"].value;
var emailreg = /^[\w._-]+[+]?[\w._-]+#[\w.-]+\.[a-zA-Z]{2,6}$/;
var usernamereg = /^[a-zA-Z0-9]+([-_\.][a-zA-Z0-9]+)*[a-zA-Z0-9])$/;
var pwdreg = /^(?=.*\d)(?=.*[a-zA-Z0-9])(?=.*[!#$%&? "])$/;
if(fName!="" && lName!="" && email!="" && username!="" && pwd!="" &&
password!="" && mobile!="")
{
if(email.match(emailreg))
{
if(username.match(usernamereg))
{
if(pwd.match(pwdreg))
{
if(pwd.match(password))
{
alert("You are Successfully Registered");
return true;
}
else
{
alert("Both Password do not match");
return false;
}
}
else
{
alert("Enter valid Password");
return false;
}
}
else
{
alert("Enter valid username");
return false;
}
}
else
{
alert("Enter a valid Email");
return false;
}
}
else
{
alert("All Fields are required");
return false;
}
}
#outer
{
height:650px;
width:1350px;
border:1px solid;
background-image:url("image.jpeg");
color:white;
font-size:22px;
}
#form
{
height:500px;
width:220px;
opacity:0.8;
margin-left:850px;
margin-top:70px;
background-color:black;
}
.a
{
height:40px;
width:180px;
border-radius:5px;
margin-top:20px;
margin-left:20px;
}
.b
{
height:40px;
width:180px;
border-radius:5px;
margin-top:20px;
margin-left:20px;
background-color:aqua;
}
<html>
<head>
</head>
<body>
<div id="outer">
<center><h2> Registration Form</h2></center>
<div id="form">
<form name="myForm" action="register.php" onsubmit="return
validateForm()" method="POST">
<input class="a" type="text" name="fName" placeholder="Enter your
first name"/>
<input class="a" type="text" name="lName" placeholder="Enter your
last name"/>
<input class="a" type="email" name="email" placeholder="Enter your
email"/>
<input class="a" type="text" name="username" placeholder="Select
your username"/>
<input class="a" type="password" name="pwd" placeholder="Enter
your password"/>
<input class="a" type="password" name="password"
placeholder="Confirm your password"/>
<input class="a" type="number" name="mobile" placeholder="Enter
your mobile no"/>
<input class="b" type="Submit" value="REGISTER"/ name="register">
</form>
</div>
</div >
</body>
</html>
Here you made several mistake in your code.
Make sure onsubmit="return validateForm()" have no any blank space before return
There is a error in your regular expression
var usernamereg = /^([a-zA-Z0-9]+([-_\.][a-zA-Z0-9]+)*[a-zA-Z0-9])$/; You made mistake in this. you forget to add ( at the starting of expression after /^
Below is the working snippet with validation.
Check it hope it will helps you
function validateForm()
{
var fName = document.forms["myForm"]["fName"].value;
var lName = document.forms["myForm"]["lName"].value;
var email = document.forms["myForm"]["email"].value;
var username = document.forms["myForm"]["username"].value;
var pwd = document.forms["myForm"]["pwd"].value;
var password = document.forms["myForm"]["password"].value;
var mobile = document.forms["myForm"]["mobile"].value;
var emailreg = /^[\w._-]+[+]?[\w._-]+#[\w.-]+\.[a-zA-Z]{2,6}$/;
var usernamereg = /^([a-zA-Z0-9]+([-_\.][a-zA-Z0-9]+)*[a-zA-Z0-9])$/;
var pwdreg = /^(?=.*\d)(?=.*[a-zA-Z0-9])(?=.*[!#$%&? "])$/;
if(fName!="" && lName!="" && email!="" && username!="" && pwd!="" &&
password!="" && mobile!="")
{
if(email.match(emailreg))
{
if(username.match(usernamereg))
{
if(pwd.match(pwdreg))
{
if(pwd.match(password))
{
alert("You are Successfully Registered");
return true;
}
else
{
alert("Both Password do not match");
return false;
}
}
else
{
alert("Enter valid Password");
return false;
}
}
else
{
alert("Enter valid username");
return false;
}
}
else
{
alert("Enter a valid Email");
return false;
}
}
else
{
alert("All Fields are required");
return false;
}
}
#outer
{
height:650px;
width:1350px;
border:1px solid;
background-image:url("image.jpeg");
color:white;
font-size:22px;
}
#form
{
height:500px;
width:220px;
opacity:0.8;
margin-left:850px;
margin-top:70px;
background-color:black;
}
.a
{
height:40px;
width:180px;
border-radius:5px;
margin-top:20px;
margin-left:20px;
}
.b
{
height:40px;
width:180px;
border-radius:5px;
margin-top:20px;
margin-left:20px;
background-color:aqua;
}
<body>
<div id="outer">
<center><h2> Registration Form</h2></center>
<div id="form">
<form name="myForm" action="register.php" onsubmit="return validateForm()" method="POST">
<input class="a" type="text" name="fName" placeholder="Enter your
first name"/>
<input class="a" type="text" name="lName" placeholder="Enter your
last name"/>
<input class="a" type="email" name="email" placeholder="Enter your
email"/>
<input class="a" type="text" name="username" placeholder="Select
your username"/>
<input class="a" type="password" name="pwd" placeholder="Enter
your password"/>
<input class="a" type="password" name="password"
placeholder="Confirm your password"/>
<input class="a" type="number" name="mobile" placeholder="Enter
your mobile no"/>
<input class="b" type="Submit" value="REGISTER"/ name="register">
</form>
</div>
</div >
</body>
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?
I have an issue, I got a form with some input type text and One input type file. I get all information AND the name of the file with jQuery and send it to a PHP page. My issue is, I want to get this file in jquery and move it in a specific folder in the server OR maybe send it to the PHP file and then I will use move_uploaded_file method.
Any help please ?
My FORM :
<div>
<p class="lead"><b>Création Push</b></p>
<form id="formAjoutpush" class='form-horizontal' action="PHP/ajoutpush.php">
<div class="form-group">
<label class="col-sm-2 control-label">Type</label>
<div class="col-xs-10">
<input id="typepush" type='text' class='form-control' placeholder="Type de Push">
</div>
</div>
<div class="form-group">
<label class="col-sm-2 control-label">Produit</label>
<div class="col-xs-10">
<input id="marche" type='text' class='form-control' placeholder="Saisie du produit">
</div>
</div>
<div class="form-group">
<label class="col-sm-2 control-label">Pays</label>
<div class="col-xs-10">
<input id="pays" type='text' class='form-control' placeholder="Localisation">
</div>
</div>
<div class="form-group">
<label class="col-sm-2 control-label">Important</label>
<input type="checkbox" id="isImportant">
</div>
<div class="form-group">
<label class="col-sm-2 control-label">Titre</label>
<div class="col-xs-10">
<input id="titrefr" style="width: 49%; display: inline" type='text' class='form-control' placeholder="Titre en Français">
<input id="titreuk" style="width: 49%; display: inline" type='text' class='form-control' placeholder="Titre en Anglais">
</div>
</div>
<div class="form-group">
<label class="col-sm-2 control-label">Contenu</label>
<div class="col-xs-10">
<textarea id="contenufr" style="width: 49%; display: inline" class='form-control' rows="7" placeholder="Contenu en Français"></textarea>
<textarea id="contenuuk" style="width: 49%; display: inline" class='form-control' rows="7" placeholder="Contenu en Anglais"></textarea>
</div>
</div>
<div class="form-group">
<label class="col-sm-2 control-label">Graph</label>
<div class="col-xs-10">
<input id="graph" type='file' name="graph" class='form-control' placeholder="Inserer un graphique" accept=".jpg,.png,.jpeg,.gif">
<div id="image" style="display: none">
<img id="preview" src="" alt="" width="300" height="200"/>
</div>
</div>
</div>
<div class='form-group'>
<div class='col-sm-offset-2 col-sm-10'>
<button id="btnValiderAjout" type='submit' class='btn btn-primary' >Valider</button>
<button type='reset' id="btnAnnulerAjout" class='btn btn-danger'>Annuler</button>
</div>
</div>
</form>
<div class="result"></div>
<div id="resultat" style="text-align: center; color: green"></div>
</div>
My Javascript :
function readURL(input) {
if (input.files && input.files[0]) {
var reader = new FileReader();
reader.onload = function (e) {
$('#preview').attr('src', e.target.result);
}
reader.readAsDataURL(input.files[0]);
}
}
$("#graph").change(function () {
$("#image").slideDown();
readURL(this);
});
$(document).ready(function () {
$('#btnValiderAjout').click(function (e) {
e.preventDefault();
var type = $('#typepush').val();
var marche = $('#marche').val();
var pays = $('#pays').val();
var titrefr = $('#titrefr').val();
var titreuk = $('#titreuk').val();
var contenufr = $('#contenufr').val();
var contenuuk = $('#contenuuk').val();
if ($('#graph').val() == '') {
} else {
var filename = $('#graph').val().replace(/C:\\fakepath\\/i, '');
var extension = filename.substr(filename.lastIndexOf(".") + 1);
var nomFinal = filename.replace(filename, $.now() + '.' + extension);
}
var idu;
var isImportant;
if ($('#isImportant').is(':checked')) {
isImportant = 1;
}
else {
isImportant = 0;
}
// test des valeurs saisies
if (type == "" || marche == "" || pays == "" || titrefr == "" || titreuk == "" || contenufr == "" || contenuuk == "") {
if (type == "") {
$('#typepush').css("border-color", "red");
$('#typepush').on('input', function () {
$('#typepush').css("border-color", "green");
});
}
if (marche == "") {
$('#marche').css("border-color", "red");
$('#marche').on('input', function () {
$('#marche').css("border-color", "green");
});
}
if (pays == "") {
$('#pays').css("border-color", "red");
$('#pays').on('input', function () {
$('#pays').css("border-color", "green");
});
}
if (titrefr == "") {
$('#titrefr').css("border-color", "red");
$('#titrefr').on('input', function () {
$('#titrefr').css("border-color", "green");
});
}
if (titreuk == "") {
$('#titreuk').css("border-color", "red");
$('#titreuk').on('input', function () {
$('#titreuk').css("border-color", "green");
});
}
if (contenufr == "") {
$('#contenufr').css("border-color", "red");
$('#contenufr').on('input', function () {
$('#contenufr').css("border-color", "green");
});
}
if (contenuuk == "") {
$('#contenuuk').css("border-color", "red");
$('#contenuuk').on('input', function () {
$('#contenuuk').css("border-color", "green");
});
}
} else {
var param = "type=" + type + "&marche=" + marche + "&pays=" + pays + "&titrefr=" + titrefr + "&titreuk=" + titreuk + "&contenufr=" + contenufr + "&contenuuk=" + contenuuk + "&isImportant=" + isImportant + "&img=" + nomFinal;
$('#resultat').load("./PHP/ajoutpush.php", param);
$("#formAjoutpush")[0].reset();
$('#resultat').delay(5000).fadeOut('slow');
$("#image").slideUp();
}
});
});
Add enctype="multipart/form-data" to form to enable upload of files
<form id="formAjoutpush" class='form-horizontal' action="PHP/ajoutpush.php" enctype="multipart/form-data">