I'm building a simple form but I'm stuck: if I send only the email field, the form validates the email and sends it
if I add two fields I can't get it to work:
I need to add the validation that the name field is not empty, and that the checkbox field is checked
$(document).ready(function($) {
var jsForm = $('.js-form-download');
jsForm.on('submit', function(e) {
var email = $(this).find('input[type=text]').val();
if (!validateEmail(email)) {
e.preventDefault();
jsForm.addClass('form-error');
}
});
// VALIDATION BEGIN
function validateEmail(email) {
var re = /^(([^<>()\[\]\.,;:\s@\"]+(\.[^<>()\[\]\.,;:\s@\"]+)*)|(\".+\"))@(([^<>()[\]\.,;:\s@\"]+\.)+[^<>()[\]\.,;:\s@\"]{2,})$/i;
return re.test(email);
}
//VALIDATION END
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<form accept-charset="UTF-8" action="/form.php" method="POST" class="main-download-form text-center js-form-download">
<input class="infusion-field-input-container" id="CustomFields_2_1" name="CustomFields[2]" type="text" placeholder="Enter Your Name" autocomplete="off" required="">
<input class="infusion-field-input-container" id="inf_field_Email" name="email" type="text" placeholder="Enter Your Email Address" autocomplete="off" required="">
<!-- field GDPR 1 REQUIRED -->
<div class="form-single--checkbox" style="max-width:400px; margin: 0 auto 20px;">
<label style="font-weight:normal;"><input type="checkbox" id="pcheck" style="width:18px; height: 18px; margin-left:0%; margin-bottom:0px;"/>Accetto il Regolamento della <a href="/privacy/" style="color: #418bbd;" target="_blank" rel="noopener"><strong>Privacy</strong></a>
</label>
</div>
<input class="btn-full" type="submit" value="Continue...">
</form>
Your issue is here var email = $(this).find('input[type=text]').val();
this will give you the first INPUT element's .val(), and if you take a closer look, the first INPUT in your form is actually the name
<input class="infusion-field-input-container" id="CustomFields_2_1" name="CustomFields[2]" type="text" placeholder="Enter Your Name" autocomplete="off" required="">
So, not the email one.
Instead, use:
var email = $(this).find('[name=email]').val();
Or, since you already use ID selectors in your HTML
var email = $("#inf_field_Email").val();