I've got this script that validates my form guestform (from bootstrap) then uses ajax to submit and it works fine and loads on the same page. However, when I added some code that when the radio button "true" is clicked it reveals a hidden part of the form (I was very proud of myself for that) this breaks my ajax submit and it goes to another page and spits out the results from my php file. How can I integrate the on clicks better?
$(document).ready(function() {
var forms = document.querySelectorAll('.needs-validation')
Array.prototype.slice.call(forms)
.forEach(function(form) {
form.addEventListener('submit', function(event) {
if (!form.checkValidity()) {
event.preventDefault()
event.stopPropagation()
}
$("#btnsub").click(function(event) {
event.preventDefault();
$.ajax({
type: "POST",
url: $('#guestForm').attr('action'),
data: $('#guestForm').serialize(),
success: function(response) {
$('#output').text(response);
}
});
});
form.classList.add('was-validated')
}, false)
});
//breaks ajax submit
$('#true').click(function(event) {
document.getElementById("guests").style.display = "block";
});
$('#false').click(function(event) {
document.getElementById("guests").style.display = "none";
});
//breaks ajax submit code
});
<form method="POST" action="insert.php" id="guestForm" class="needs-validation" novalidate>
<div class="col-6">
<label for="party" class="form-label">Your Name</label>
<input type="text" class="form-control" id="party" name="party" minlength="4" maxlength="50" aria-describedby=inputGroup-sizing-default " required>
<div class="invalid-feedback ">Please Enter your full name.</div>
</div>
<div class="form-label ">Will you be joining us ?"</div>
<div class="form-check">
<input type="radio" class="form-check-input" id="true" name="att" required />
<label class="form-check-label" for="true">Joyfully accepts</label>
</div>
<div class="form-check">
<input type="radio" class="form-check-input" id="false" name="att" required />
<label class="form-check-label" for="false">Regretfully declines</label>
<div class="invalid-feedback">Please choose a response.</div>
</div>
<div class="col-6" id="guests" name="guests" style="display: none">
<p>If you are bringing a +1, please enter their name here.</p><br>
<label for="guest1" class="form-label">Guest Name</label>
<input type="text" class="form-control" id="guest1" name="guest1" placeholder="Optional" minlength="4" maxlength="50">
<div class="invalid-feedback">Please Enter their full name.</div>
</div>
<button type="submit" class="btn btn-primary" id="btnsub" name="btnsub">Submit</button>
<div id="output"></div>
</form>
Related
I'm trying to create a form which will send an email to the user on submit.
The thing is that I used Bootstrap's form template and when I submit it with phone and mail wrong values (phone number even empty), the email is sent anyway (with 200 ok) and a success alert is showing.
Here is my HTML code:
<form class="needs-validation" novalidate id="paymentForm">
<div class="row">
<div class="col-md-6 mb-3">
<label for="firstName">First Name</label>
<input type="text" class="form-control" name="firstName" id="firstName" placeholder="" value="" required>
<div class="invalid-feedback">
required Feild
</div>
</div>
<div class="col-md-6 mb-3">
<label for="lastName">Lasr Name</label>
<input type="text" class="form-control" name="lastName" id="lastName" placeholder="" value="" required>
<div class="invalid-feedback">
required Feild
</div>
</div>
</div>
<div class="mb-3">
<label for="email">Email</label>
<input type="email" class="form-control" value="" name="email" id="email" placeholder="you#example.com" required>
<div class="invalid-feedback">
please enter a valid mail address
</div>
</div>
<div class="mb-3">
<label for="phone">Phone Number</label>
<input type="tel" class="form-control" value="" name="phone" placeholder="example: 050-1111111" pattern="[0]{1}[5]{1}[0-9]{8}" id="phone" required>
<div class="invalid-feedback">
please provide a valid phone number
</div>
</div>
<div class="mb-3">
<label for="address"> address</label>
<input type="text" class="form-control" name="address" id="address" placeholder="" required>
<div class="invalid-feedback">
please provide your address
</div>
</div>
<hr class="mb-4">
<h4 class="mb-3">payment method</h4>
<div class="d-block my-3">
<div class="custom-control custom-radio">
<input id="cash" value="cash" value="cash" name="paymentMethod" type="radio" class="custom-control-input" required checked>
<label class="custom-control-label" for="cash">cash</label>
</div>
<div class="custom-control custom-radio">
<input id="bit" value="bit" value="bit" name="paymentMethod" type="radio" class="custom-control-input" required>
<label class="custom-control-label" for="bit">Bit</label>
</div>
</div>
<div class="invalid-feedback">
please choose method
</div>
<hr class="mb-4">
<button class="btn btn-primary btn-lg btn-block" type="submit">continue to checkout</button>
</form>
and here is my js:
(function() {
'use strict'
window.addEventListener('load', function() {
var forms = document.getElementsByClassName('needs-validation')
Array.prototype.filter.call(forms, function(form) {
form.addEventListener('submit', function(event) {
var radioValue = $('#paymentForm input:radio:checked').val()
if (form.checkValidity() === false) {
event.preventDefault();
event.stopPropagation();
}
form.classList.add('was-validated')
var orderNumber = generateId();
var cName = $('#firstName').val() + " " + $('#lastName').val()
var cEmail = $('#email').val()
var cPhone = $('#phone').val()
var cAddress = $('#address').val()
var cSumToPay = parseInt(localStorage.getItem("totalPrice"));
var cProducts = JSON.parse(localStorage.getItem("products") || "[]");
cProducts = cProducts.map(Object.values);
cProducts = cProducts.join(' ');
console.log(cProducts);
var templateParams = {
order_number: orderNumber,
customer_name: cName,
products: cProducts,
addres: cAddress,
phone: cPhone,
customer: cEmail,
payment_Methode: radioValue,
customer_sum: cSumToPay
};
emailjs.send('gmail', 'orderconfirmation', templateParams)
.then(function(response) {
console.log('SUCCESS!', response.status, response.text);
alert('Yey! Your email was sent :)');
}, function(error) {
console.log('error');
alert(error);
});
event.preventDefault();
}, false)
})
}, false)
}())
I would be thankful if you guys can help me!!!
This section appears to be your only check for validation:
if (form.checkValidity() === false) {
event.preventDefault();
event.stopPropagation();
}
However, event.preventDefault() and event.stopPropagation() are not going to prevent the code from falling through to the next section. You can do that by including a return at this point
if (form.checkValidity() === false) {
event.preventDefault();
event.stopPropagation();
return false;
}
or you can wrap the rest of your code in the else of your conditional
if (form.checkValidity() === false) {
event.preventDefault();
event.stopPropagation();
} else {
// your email handling code
}
Note: your event.preventDefault() is useful to stop the submit button from performing its default behavior of submitting the form and event.stopPropagation() will just keep the event from bubbling up to parent elements (which you likely don't need). See: https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault and https://developer.mozilla.org/en-US/docs/Web/API/Event/stopPropagation
In any case, you do not need two event.preventDefault() calls if you place a single one at the top of your event listener, e.g.
form.addEventListener('submit', function(event) {
event.preventDefault();
...
I have a form that is being used as a basic contact form. I have added a checkbox that adds some fields if selected. How can I change the onclick action of the submit button based on if this box is checked or not. Here is what I have currently.
<form class="homeContact">
<label for="chkJob">
Interested in a career? Check to apply
<input type="checkbox" id="chkJob" />
</label>
<div id="dvApply" style="display: none">
Download Application
Download the application. Fill it out and upload below:
<input type="file" name="fileToUpload" id="fileToUpload">
</div>
<div id="popErr"></div>
<input type="hidden" name="nospam">
<div class="field">
<div class="label-form">
<input type="text" placeholder="Name *" value="" name="name" id="popName">
<span class="form-icon fa fa-user"></span>
</div>
</div>
<div class="field">
<div class="label-form">
<input type="text" placeholder="Email *" value="" name="email" id="popEmail">
<span class="form-icon fa fa-envelope"></span>
</div>
</div>
<div class="field">
<div class="label-form">
<input type="text" placeholder="Phone *" value="" name="phone" id="popTel">
<span class="form-icon fa fa-phone"></span>
</div>
</div>
<div id="submit_button">
<input type="button" class="button submit" id="contact-submit" onclick="submitForm()" value="Request Information">
</div>
</form>
<script>
jQuery(document).ready(function($) {
$("#chkJob").click(function () {
if ($(this).is(":checked")) {
$("#dvApply").show();
} else {
$("#dvApply").hide();
}
});
});
</script>
You can implement this login into your submitForm function:
function submitForm()
{
if ($('#chkJob').is(":checked")) {
$("#dvApply").show();
} else {
$("#dvApply").hide();
}
}
But if you want dvApply to be toggled every time checkbox button is clicked without waiting for submit button to be clicked you can do something like:
jQuery(document).ready(function($) {
$('#chkJob').change(function() {
$('#dvApply').toggle();
});
});
I have a fairly straightforward validation function that only checks if input is empty or not. I'm using it across a half dozen different forms and it seems to be working everywhere except one specific input id="driver_first_name" . Can't figure out why it fails there.
If I leave all fields empty I get errors on all of them, and is generally correct across any combination I have tried except driver_first_name In the case that I fill out everything except driver_first_name the form submits anyways.
Any insight on what might be going on here?
Thank you!
My Validation function is this:
function validateForm(form, fields) { //add exit anbimation and reset the container state
$(".form-input-error").remove();
var result=false;
$.each( fields.rules, function( key, value ) {
if(!$("#"+key+"").val()){
$("#"+key+"").addClass("form-error");
$( "<div class='form-input-error'>"+value.message+"</div>" ).insertBefore("#"+key+"");
result = false;
//console.log(this.val());
}
else{
$("#"+key+"").removeClass("form-error");
result = true;
}
});
return result;
}
I am calling my validation on my submit triggers, generally like this for fields that should not be empty:
$(".app-canvas").on('click', ".submitNewDriver", function () {//list all drivers trigger
var checkInputs = {
rules: {
driver_first_name: {
message: "First Name is Required"
},
driver_last_name: {
message: "Last Name is Required"
},
driver_address_street: {
message: "street is Required"
}
}
};
if(validateForm($("#addDriverForm"),checkInputs) == true){
console.log("form submit");
addNewDriver();
}
else{
console.log("form errors");
}
});
My full form HTML is
<div class="form-wrapper">
<form id="addDriverForm" class="post-form" action="modules/add_driver.php" method="post">
<div class="form-row">
<label for="driver_first_name">First Name:</label>
<input id="driver_first_name" placeholder="John" type="text" name="driver_first_name">
</div>
<div class="form-row">
<label for="driver_last_name">Last Name:</label>
<input id="driver_last_name" placeholder="Smith" type="text" name="driver_last_name">
</div>
<div class="form-row">
<label for="driver_address_street">Street</label>
<input id="driver_address_street" placeholder="123 Main St." type="text" name="driver_address_street">
</div>
<div class="form-row">
<label for="driver_address_city">City</label>
<input id="driver_address_city" placeholder="Chicago" type="text" name="driver_address_city">
</div>
<div class="form-row">
<label for="driver_address_state">State</label>
<input id="driver_address_state" placeholder="IL" type="text" name="driver_address_state">
</div>
<div class="form-row">
<label for="driver_address_zip">Zip</label>
<input id="driver_address_zip" placeholder="60164" type="number" name="driver_address_zip">
</div>
<div class="form-row">
<label for="driver_telephone">Zip</label>
<input id="driver_telephone" placeholder="60164" type="tel" name="driver_telephone">
</div>
<div class="form-row">
<label for="driver_email">E-Mail</label>
<input id="driver_email" placeholder="60164" type="email" name="driver_email">
</div>
<div class="form-row"><label for="driver_payment_type">Settlement Type</label>
<select id="driver_payment_type" name="driver_payment_type">
<option value="flat">Flat Rate</option>
<option value="percent">Percent</option>
<option value="mile">Per Mile</option>
</select></div>
<div class="form-row">
<label for="driver_license_number">Lisence #</label>
<input id="driver_license_number" placeholder="ex:D400-7836-2633" type="number" name="driver_license_number">
</div>
<div class="form-row">
<label for="driver_license_expiration">Lisence Expiration Date</label>
<input id="driver_license_expiration" type="date" name="driver_license_expiration">
</div>
<div class="form-row">
<label for="driver_licence_image">Lisence Copy</label>
<input id="driver_licence_image" type="file" name="driver_licence_image">
</div>
<div class="form-row">
<label for="driver_medical_certificate_expiration">Medical Certificate Expiration</label>
<input id="driver_medical_certificate_expiration" type="date" name="driver_medical_certificate_expiration">
</div>
<div class="form-row">
<label for="driver_medical_certificate_image">Medical CXertificate Copy</label>
<input id="driver_medical_certificate_image" type="file" name="driver_medical_certificate_image">
</div>
<div class="form-row">
<label class="driverCheckbox" for="driver_access_mobile_app">Allow Mobile Access</label>
<input id="driver_access_mobile_app" checked value="1" type="checkbox" name="driver_access_mobile_app">
</div>
<div class="form-row"></div>
<div class="driver-access-copnditional">
<div class="form-row">
<label for="driver_username">Username</label>
<input id="driver_username" placeholder="JohSmi" type="text" name="driver_username">
</div>
<div class="form-row">
<label for="driver_password">Password</label>
<input id="driver_password" placeholder="***" type="password" name="driver_password">
</div>
</div>
<div class="clear"></div>
<div class="submitNewUnit button green"><i class="material-icons">save</i>Submit</div>
</form>
</div>
Your validation logic is a little messed up. This is what's happening:
#driver_first_name is validated as invalid... result is set false
#driver_last_name is validated as valid... result is set true
#driver_address_street is validated as valid... result is set true
After all that the code thinks the form is valid. You're only preventing the form from being submitted if the last field as validated as not-valid.
Change your logic to assume the form is valid from the beginning. Then set it to false if any of the fields are invalid.
I also don't see anything in your code that actually prevents the form submition, so I also added e.preventDefault()
function validateForm(form, fields) { //add exit anbimation and reset the container state
$(".form-input-error").remove();
var result = true;
$.each(fields.rules, function(key, value) {
if (!$("#" + key + "").val()) {
$("#" + key + "").addClass("form-error");
$("<div class='form-input-error'>" + value.message + "</div>").insertBefore("#" + key + "");
result = false;
//console.log(this.val());
} else {
$("#" + key + "").removeClass("form-error");
}
});
return result;
}
$(".app-canvas").on('click', ".submitNewDriver", function(e) { //list all drivers trigger
var checkInputs = {
rules: {
driver_first_name: {
message: "First Name is Required"
},
driver_last_name: {
message: "Last Name is Required"
},
driver_address_street: {
message: "street is Required"
}
}
};
if (validateForm($("#addDriverForm"), checkInputs) == true) {
console.log("form submit");
} else {
e.preventDefault();
console.log("form errors");
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="app-canvas form-wrapper">
<form id="addDriverForm" class="post-form" action="" method="post">
<div class="form-row">
<label for="driver_first_name">First Name:</label>
<input id="driver_first_name" placeholder="John" type="text" name="driver_first_name">
</div>
<div class="form-row">
<label for="driver_last_name">Last Name:</label>
<input id="driver_last_name" placeholder="Smith" type="text" name="driver_last_name">
</div>
<div class="form-row">
<label for="driver_address_street">Street</label>
<input id="driver_address_street" placeholder="123 Main St." type="text" name="driver_address_street">
</div>
<div class="form-row">
<label for="driver_address_city">City</label>
<input id="driver_address_city" placeholder="Chicago" type="text" name="driver_address_city">
</div>
<div class="form-row">
<label for="driver_address_state">State</label>
<input id="driver_address_state" placeholder="IL" type="text" name="driver_address_state">
</div>
<div class="form-row">
<label for="driver_address_zip">Zip</label>
<input id="driver_address_zip" placeholder="60164" type="number" name="driver_address_zip">
</div>
<div class="form-row">
<label for="driver_telephone">Zip</label>
<input id="driver_telephone" placeholder="60164" type="tel" name="driver_telephone">
</div>
<div class="form-row">
<label for="driver_email">E-Mail</label>
<input id="driver_email" placeholder="60164" type="email" name="driver_email">
</div>
<div class="form-row"><label for="driver_payment_type">Settlement Type</label>
<select id="driver_payment_type" name="driver_payment_type">
<option value="flat">Flat Rate</option>
<option value="percent">Percent</option>
<option value="mile">Per Mile</option>
</select></div>
<div class="form-row">
<label for="driver_license_number">Lisence #</label>
<input id="driver_license_number" placeholder="ex:D400-7836-2633" type="number" name="driver_license_number">
</div>
<div class="form-row">
<label for="driver_license_expiration">Lisence Expiration Date</label>
<input id="driver_license_expiration" type="date" name="driver_license_expiration">
</div>
<div class="form-row">
<label for="driver_licence_image">Lisence Copy</label>
<input id="driver_licence_image" type="file" name="driver_licence_image">
</div>
<div class="form-row">
<label for="driver_medical_certificate_expiration">Medical Certificate Expiration</label>
<input id="driver_medical_certificate_expiration" type="date" name="driver_medical_certificate_expiration">
</div>
<div class="form-row">
<label for="driver_medical_certificate_image">Medical CXertificate Copy</label>
<input id="driver_medical_certificate_image" type="file" name="driver_medical_certificate_image">
</div>
<div class="form-row">
<label class="driverCheckbox" for="driver_access_mobile_app">Allow Mobile Access</label>
<input id="driver_access_mobile_app" checked value="1" type="checkbox" name="driver_access_mobile_app">
</div>
<div class="form-row"></div>
<div class="driver-access-copnditional">
<div class="form-row">
<label for="driver_username">Username</label>
<input id="driver_username" placeholder="JohSmi" type="text" name="driver_username">
</div>
<div class="form-row">
<label for="driver_password">Password</label>
<input id="driver_password" placeholder="***" type="password" name="driver_password">
</div>
</div>
<div class="clear"></div>
<input type="submit" class="submitNewDriver button green" value="Submit" />
</form>
</div>
I have html form and localstorage
I need send data from localstorage and form on email
Now I am sending two letter :(
When user submit form I get two letter. First letter from form and second letter from localstorage
So, I want get one letter with localstorage and form
My form:
<form action="/send.php" id="form-cart-send" onsubmit="return sendCartdata();" method="post" enctype="multipart/form-data" required>
<div class="form_fields" data-count="3">
<div class="form_field" data-type="name" data-is-required="true">
<label class="field_title">Имя<i>*</i></label>
<div class="form_field_text">
<input type="text" class="form_field_text_input" name="name" autocomplete="off" required>
</div>
</div>
<div class="form_field" data-type="phone" data-is-required="1">
<label class="field_title">Телефон<i>*</i></label>
<div class="form_field_text">
<input type="tel" class="form_field_text_input form_phone" id="phone" name="phone" data-check="phone" autocomplete="off" required>
</div>
</div>
<div class="form_field" data-type="email" data-is-required="0">
<label class="field_title">Ваш e-mail</label>
<div class="form_field_text">
<input type="text" class="form_field_text_input" name="email" data-check="email" autocomplete="off" required>
</div>
</div>
</div>
<div class="form_fields_advanced"></div>
<div class="form_submit">
<a class="component-button form_field_submit filled squared" id="checkout" data-modal-id="cart_done">
<div class="btn-content">
<div class="form_submit_text">Заказать</div>
</div>
</a>
</div>
</form>
Script for localstorage:
<script>
function sendCartdata() {
var phone = document.getElementById("phone").value;
if (phone === '') {
alert("Заполните, пожалуйста, обязательные поля.");
return false;
} else {
setTimeout(function() {
var value = localStorage.getItem('cart');
jQuery.post("/cart-send.php", {
cart: value
}, function(data) {
}).fail(function() {
alert("Damn, something broke");
});
}, 100);
return false;
}
}
</script>
In the HTML, the forms look identical, just the form ID is changed. I use this JS file to submit the forms using AJAX:
$("#change-password").submit(function(e) {
var url = "http://domain/actions";
$.ajax({
type: "POST",
url: url,
data: $("#change-password").serialize(),
success: function(data) {
$("div.change-password-response").html(data);
}
});
e.preventDefault();
});
$("#change-email").submit(function(e) {
var url = "http://domain/actions";
$.ajax({
type: "POST",
url: url,
data: $("#change-email").serialize(),
success: function(data) {
$("div.change-email-response").html(data);
}
});
e.preventDefault();
});
HTML Part
<div class="col-md-6 col-sm-6 add_bottom_30">
<h4>Schimbare parola</h4>
<form id="change-password" method="post">
<div class="form-group">
<label>Parola veche</label>
<input class="form-control" name="old_password" id="old_password" type="password" autocomplete="off">
</div>
<div class="form-group">
<label>Parola noua</label>
<input class="form-control" name="new_password" id="new_password" type="password" autocomplete="off">
</div>
<div class="form-group">
<label>Confirma parola noua</label>
<input class="form-control" name="confirm_new_password" id="confirm_new_password" type="password" autocomplete="off">
</div>
<input type="hidden" name="action" value="change-password">
<button type="submit" class="btn_1 green">Actualizeaza parola</button>
<div class="change-password-response form-response"></div>
</form>
</div>
<div class="col-md-6 col-sm-6 add_bottom_30">
<h4>Schimbare adresa email</h4>
<form id="change-email" method="post">
<div class="form-group">
<label>Email vechi</label>
<input class="form-control" name="old_email" id="old_email" type="text" autocomplete="off">
</div>
<div class="form-group">
<label>Email nou</label>
<input class="form-control" name="new_email" id="new_email" type="text" autocomplete="off">
</div>
<div class="form-group">
<label>Confirma email nou</label>
<input class="form-control" name="confirm_new_email" id="confirm_new_email" type="password" autocomplete="off">
</div>
<input type="hidden" name="action" value="change-email">
<button type="submit" class="btn_1 green">Actualizeaza Email</button>
<div class="change-email-response form-response"></div>
</form>
</div>
Now, my problem is that Form 1 is working, Form 2 is not triggering the AJAX and works as normal form. What am I doing wrong?
Check if #change-email has other binded events.
In Firebug, inspect #change-email element and go to Event tab.
In Chrome, inspect that element and go to Event Listeners tab.
You will see all binded events and corresponded callback functions.
If it will not help, try to submit a form manually from Console
Inspect a form, then run
$($0).submit();
If it will work, looks like you have some events on you button.