I'm using some Ajax / Javascript to prevent the form submit if an input field is empty.
$(function() {
var form = $('#contact-form-edc');
$(form).submit(function(e) {
e.preventDefault();
var formData = $(form).serialize();
if (document.getElementById("nachricht-field").value.length < 10) {
document.getElementById('error-nachricht').style.display = "";
} else {
$.ajax({
type: 'POST',
url: $(form).attr('action'),
data: formData
})
.done(function(response) {
document.getElementById('success').style.display = "";
document.getElementById('error').style.display = "none";
document.getElementById('error-nachricht').style.display = "none";
$('input').val('');
$('textarea').val('');
$('.button').val('Abschicken');
$('input[name=datenschutz]').attr('checked', false);
})
.fail(function(data) {
document.getElementById('error').style.display = "";
document.getElementById('success').style.display ="none";
});
}
});
});
The script works fine but do not note the checkbox of the form. The checkbox
<input type="checkbox" name="datenschutz" value="Datenschutz" required="required" >
is required as well but the user can submit the form without checking the checkbox. Is there a small script which I can implement in the current Ajax-Script?
Use this way:
$(form).submit(function(e) {
e.preventDefault();
if ($(this).find('input[name="datenschutz"]')[0].checked === false)
return false;
// rest of form
If you want to add a message, you can go ahead this way:
$(form).submit(function(e) {
e.preventDefault();
if ($(this).find('input[name="datenschutz"]')[0].checked === false) {
alert("Please accept the terms and conditions!");
return false;
}
// rest of form
I'd suggest enabling the submit button when the check-box is checked:
// binding an anonymous function to handle the change event:
$('input[name=datenschutz]').on('change', function () {
var input = this;
// navigating to the form 'this.form',
// finding the submit button (obviously correct the
// selector),
// setting the disabled property of the submit button to
// to be false when the check-box is checked, and true
// when the check-box is unchecked:
$(input.form).find('submitButtonSelector').prop('disabled', !input.checked});
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With