I have the following if that, so far, the only thing it does is to not let it trigger the form ajax submission if any input is blank. Being empty is one of the conditions but besides that, I'd also like it to prevent the form from being sent if a required filling pattern for each field is not respected. I've tried some things but they didn't work, so I guess I'm probably making mistakes regarding the synthax or other details. What would be the best way to do it?
(function($){
$('#enquiry').submit( function(event){
event.preventDefault();
var fname = $.trim($('.fname').val());
var lname = $.trim($('.lname').val());
var email = $.trim($('.email').val());
var subject = $.trim($('.subject').val());
var message = $.trim($('.message').val());
if (fname === '' || lname === '' || email === '' || subject === '' || message === ''){
alert('trigger error message')
}
else{
alert('ajax call sending the data')
}
Here's the form code, in case it's relevant:
<form id="enquiry" method="post" onsubmit="return false">
<div class="form">
<input class="input fname" placeholder="a" name="fname" type="text" autocomplete='off' pattern="[a-zA-Z]{1,36}" required></input>
<label for="namef" class="">Your name</label>
</div>
<div class="form">
<input class="input lname" placeholder="a" name="lname" type="text" autocomplete='off' pattern="[a-zA-Z]{1,36}" required></input>
<label for="surname" class="">Your surname</label>
</div>
<div class="form">
<input class="input email" placeholder="a" name="email" type="text" autocomplete='off' pattern="[^#\s]+#[^#\s]+\.[^#\s]+" required></input>
<label for="email" class="">Your email</label>
</div>
<div class="form custom-select">
<select class="input subject" name="subject" autocomplete='off' required>
<option>Option 1</option>
<option>Option 2</option>
<option>Option 3</option>
</select>
</div>
<div class="form2">
<textarea class="input message" placeholder="a" name="message" autocomplete='off' pattern="[0-9a-zA-Z- ]" required></textarea>
<label for="tellme" class="">Tell me something</label>
</div>
<div class="contactbutton">
<button type="submit" class="button" role="button"><span>SUBMIT</span></button>
</div>
</form>
Related
I have a form created using HTML and I have a submit button.
I am trying to have the submit button disabled if the fields are not filled out.
However, now even if the fields are filled out the button stays disabled.
const subButton = document.querySelector('.sbutton')
const inputTexts = document.querySelector('.input')
subButton.disabled = true
function clickedButton() {
if (document.querySelector('.input').value === "") {
subButton.disabled = true
} else {
subButton.disabled = false
}
}
<div class="form">
<section>
<form action=[link] method="POST">
<fieldset>
<legend>Your Contact Info!</legend>
<label class="firstname" for="firstname">First Name</label>
<input class="input" type="text" id="firstname" name="name" placeholder="Your first name" required>
<label class="lastname" for="lastname">Last Name</label>
<input type="text" id="lastname" name="lname" placeholder="Your last name">
<label class="email" for="email">E-mail</label>
<input class="input" type="email" id="email" name="email" placeholder="Your e-mail" required>
<label class="comments" for="comments">Additional Comments</label>
<textarea class="input" placeholder="Anything else we should know!" id="comments" name="comments" required></textarea>
<label class='input' for="timeofday">When is the best time of day to contact you?</label>
<select id="timeofday" name="timeofday">
<option value='Morning'>Morning</option>
<option selected value="afternoon">Afternoon</option>
<option value="evening">Evening</option>
</select>
</fieldset>
<button class="sbutton" type="submit">Submit</button>
The issue is, that you never call the function clickedButton(). You need an eventListener that listens for change events within the inputs and then calls that function:
const INPUTS = document.querySelectorAll('input');
INPUTS.forEach(el =>
el.addEventListener('change', clickedButton)
)
const subButton = document.querySelector('.sbutton')
const inputTexts = document.querySelector('.input')
const INPUTS = document.querySelectorAll('input');
subButton.disabled = true
INPUTS.forEach(el =>
el.addEventListener('change', clickedButton)
)
function clickedButton() {
if (document.querySelector('.input').value === "") {
subButton.disabled = true
} else {
subButton.disabled = false
}
}
<div class="form">
<section>
<form action=[link] method="POST">
<fieldset>
<legend>Your Contact Info!</legend>
<label class="firstname" for="firstname">First Name</label>
<input class="input" type="text" id="firstname" name="name" placeholder="Your first name" required>
<label class="lastname" for="lastname">Last Name</label>
<input type="text" id="lastname" name="lname" placeholder="Your last name">
<label class="email" for="email">E-mail</label>
<input class="input" type="email" id="email" name="email" placeholder="Your e-mail" required>
<label class="comments" for="comments">Additional Comments</label>
<textarea class="input" placeholder="Anything else we should know!" id="comments" name="comments" required></textarea>
<label class='input' for="timeofday">When is the best time of day to contact you?</label>
<select id="timeofday" name="timeofday">
<option value='Morning'>Morning</option>
<option selected value="afternoon">Afternoon</option>
<option value="evening">Evening</option>
</select>
</fieldset>
<button class="sbutton" type="submit">Submit</button>
Note, that you check only the first input. querySelector returns only 1 element (the first).
Nothing on the page is calling clickedButton()
Attach an EventListener for changes on the form that calls this function.
var form = document.querySelector('form');
form.addEventListener('change', clickedButton);
Also when you are using querySelector you will only get the first element in the form which is a <input .... If you want to check for all you should use querySelectorAll.
But that function would return an array so then you need to check if all of them have text.
In that case you could do it like this.
function validateForm() {
// Get all elements
const elements = document.querySelectorAll("input");
// Filter out elements that have no value, if there is more then 1 set disabled to true, else it is false
const disabled = elements.filter((el) => el.value === "").length > 0 ? true : false;
subButton.disabled = disabled
}
And if you are going with this way you need to call this function instead of the other one like this:
var form = document.querySelector('form');
form.addEventListener('change', validateForm);
I have a simple form where I am using a vanilla JS library (https://pristine.js.org/) for form validation. The form validation is successful (mostly) but then the form doesn't submit. For the life of me I can't figure out what's going wrong.The form is supposed to post to a PHP file where I can get the posted variable values.
My HTML page with the form and necessary JS and CSS are in the jsfiddle here. In case JSFiddle is acting up, the actual code's below.
I'd appreciate it if someone can help me out with this.
Thanks a ton!
Dexxterr
P.S.: I've beginner level knowledge about JS.
My HTML Code:
<div style="width: 50%; margin: auto;">
<form class="fv-stacked-form" id="inquiry" method="POST" action="form.php">
<div class="fv-row form-group">
<label>Which industry does your organization belong to?</label>
<div>
<input class="form-control" type="checkbox" name="industry[]" value="Manufacturing" id="indManufacturing" min="1" required data-pristine-min-message="Select at least 1" />
<label class="label-inline" for="indManufacturing">Manufacturing</label>
</div>
<div>
<input class="form-control" type="checkbox" name="industry[]" value="Education" id="indEducation" min="1" required data-pristine-min-message="Select at least 1" />
<label class="label-inline" for="indEducation">Education</label>
</div>
<div>
<input class="form-control" type="checkbox" name="industry[]" value="Real Estate" id="indRealestate" min="1" required data-pristine-min-message="Select at least 1" />
<label class="label-inline" for="indRealestate">Real Estate</label>
</div>
<div>
<input class="form-control" type="checkbox" name="industry[]" value="" id="indOther" min="1" required data-pristine-min-message="Select at least 1" />
<label class="label-inline" for="indOther">Other</label>
<input style="display: none;" class="label-inline" type="text" name="indOtherValue" id="indOtherValue" value="" minlength="3" class="form-control" data-pristine-min-message="Please enter your industry" />
</div>
</div>
<div class="fv-row form-group">
<label>What is your budget? (In USD)</label>
<input class="form-control" type="number" min="100" required name="budget" data-pristine-min-message="Enter at least 100" />
</div>
<div class="fv-row form-group">
<label>How soon do you want to get started??</label>
<div>
<input class="form-control" type="radio" name="timeline[]" value="Immediately" id="immediately" required />
<label class="label-inline" for="immediately">Immediately</label>
</div>
<div>
<input class="form-control" type="radio" name="timeline[]" value="3Months" id="3months" required />
<label class="label-inline" for="3months">In the next 3 months</label>
</div>
<div>
<input class="form-control" type="radio" name="timeline[]" value="6Months" id="6months" required />
<label class="label-inline" for="6months">In the next 6 months</label>
</div>
<div>
<input class="form-control" type="radio" name="timeline[]" value="NoIdea" id="noidea" required />
<label class="label-inline" for="noidea">I don't have a timeline yet</label>
</div>
</div>
<div class="fv-row form-group">
<label>First Name</label>
<input class="form-control" type="text" name="fname" required />
</div>
<div class="fv-row form-group">
<label>Last Name</label>
<input class="form-control" type="text" name="lname" required />
</div>
<div class="fv-row form-group">
<label>Company Email</label>
<input class="form-control" type="email" name="email" required />
</div>
<div class="fv-row form-group">
<label>No. of Employees</label>
<select class="form-control" id="ageRangeField" required>
<option value=""></option>
<option value="1-100">1-100</option>
<option value="100-500">100-500</option>
<option value="500-2500">500-2500</option>
<option value="2500+">2500+</option>
</select>
</div>
<div class="fv-row form-group">
<input name="formsubmit" id="formsubmit" type="submit" class="" value="Submit" />
</div>
</form>
<p id="confmsg" style="display: none;">Thank you for submitting the form.</p>
</div>
My JS Code:
window.onload = function ()
{
var form = document.getElementById("inquiry");
var pristine = new Pristine(form);
form.addEventListener('submit', function (e)
{
e.preventDefault();
var valid = pristine.validate();
// alert('Form is valid: ' + valid);
if(valid === true)
{
// alert("This works");
return true;
}
else
{
// alert("This doesn't work");
}
});
};
var sb = document.getElementById('formsubmit'); // Submit button
var cbother = document.getElementById('indOther'); // Checkbox
var txtother = document.getElementById('indOtherValue'); // Other Textbox
cbother.addEventListener('click',function(e){
if(cbother.checked){
cbother.value=txtother.value;
txtother.style.display = 'block';
}else{
txtother.value='';
txtother.style.display = 'none';
}
},false);
e.preventDefault();
is preventing the form from being submitted. If you simply remove it the form will be submitted even if the pristine check fails. So what you want to do is only prevent the default behaviour (which is the form to be submitted) if the pristine check fails:
form.addEventListener('submit', function (e)
{
var valid = pristine.validate();
// alert('Form is valid: ' + valid);
if(valid === true)
{
// alert("This works");
return true;
}
else
{
e.preventDefault();
// alert("This doesn't work");
}
});
to simplify that a little you could simply write:
form.addEventListener('submit', function (e)
{
//if the pristine check fails, prevent the form from being submitted
if(!pristine.validate()){
e.preventDefault();
}
});
I am have a small script written in JS for a form. The script looks like so:
$(document).ready(function() {
// Test for placeholder support
$.support.placeholder = (function(){
var i = document.createElement('input');
return 'placeholder' in i;
})();
// Hide labels by default if placeholders are supported
if($.support.placeholder) {
$('.form-label').each(function(){
$(this).addClass('js-hide-label');
});
// Code for adding/removing classes here
$('.form-group').find('input, textarea').on('keyup blur focus', function(e){
console.log(e);
// Cache our selectors
var $this = $(this),
$parent = $this.parent().find("label");
if (e.type == 'keyup') {
if( $this.val() == '' ) {
$parent.addClass('js-hide-label');
} else {
$parent.removeClass('js-hide-label');
}
}
else if (e.type == 'blur') {
if( $this.val() == '' ) {
$parent.addClass('js-hide-label');
}
else {
$parent.removeClass('js-hide-label').addClass('js-unhighlight-label');
}
}
else if (e.type == 'focus') {
if( $this.val() !== '' ) {
$parent.removeClass('js-unhighlight-label');
}
}
});
}
});
and this is my form in HTML:
<form id="contact-form" class="form" action="#" method="POST" role="form">
<div class="form-group">
<label class="form-label" for="name">Your Name</label>
<input type="text" class="form-control" id="name" name="name" placeholder="Your Name" required>
</div>
<div class="form-group">
<label class="form-label" for="email">Your Email</label>
<input type="email" class="form-control" id="email" name="email" placeholder="Your Email" required>
</div>
<div class="form-group">
<label class="form-label" for="subject">Subject</label>
<input type="text" class="form-control" id="subject" name="subject" placeholder="Subject">
</div>
<div class="form-group">
<label class="form-label" for="message">Message</label>
<textarea rows="5" cols="50" name="message" class="form-control" id="message" placeholder="Message..." required></textarea>
</div>
<div class="text-center">
<button type="submit" class="btn btn-start-order">Send Message</button>
</div>
</form>
This works well, as can be seen here: https://codepen.io/stephanrusu/pen/QwKLJX
I have modified my form to have a <span></span> tags around the input/textarea. In the JS this requires looking for input and textfield inside the span which has class name wpcf7-form-control-wrap. So my HTML looks like this now:
<form id="contact-form" class="form" action="#" method="POST" role="form">
<div class="form-group">
<label class="form-label" for="name">Your Name</label>
<span class="wpcf7-form-control-wrap fullname">
<input type="text" class="form-control" id="name" name="name" placeholder="Your Name" required>
</span>
</div>
<div class="form-group">
<label class="form-label" for="email">Your Email</label>
<span class="wpcf7-form-control-wrap email">
<input type="email" class="form-control" id="email" name="email" placeholder="Your Email" required>
</span>
</div>
<div class="form-group">
<label class="form-label" for="subject">Subject</label>
<span class="wpcf7-form-control-wrap subject">
<input type="text" class="form-control" id="subject" name="subject" placeholder="Subject">
</span>
</div>
<div class="form-group">
<label class="form-label" for="message">Message</label>
<span class="wpcf7-form-control-wrap message">
<textarea rows="5" cols="50" name="message" class="form-control" id="message" placeholder="Message..." required></textarea>
</span>
</div>
<div class="text-center">
<span class="wpcf7-form-control-wrap fullname">
<button type="submit" class="btn btn-start-order">Send Message</button>
</span>
</div>
</form>
So my questions is how can the JS be modified to work with the following form. All that is added is around the inputs and textareas.
Many thanks in anticipation.
In your code, just change the line:
$parent = $this.parent().find("label");
to
$parent = $this.closest(".form-group").find("label");
After update of form, $(this).parent() refers to <span> instead of <label>. $this.closest(".form-group").find("label") will refer correctly to label elements.
I'm doing a client-side form validation while setting the custom warning messages, but that same pop-up message keeps showing even when the input is filled with the name.
For example i have an input field to get the user name on the code below:
<form id="form" name="contactForm" method="post" action="php/formulario_contactos.php">
<div>
<label for="name">Your name</label>
<input type="text" id="name" name="name" required="">
</div>
<div>
<label for="mail">Your email</label>
<input type="email" id="mail" name="user_mail" required="">
</div>
<div>
<label for="topic">Select Topic</label>
<select id="topic" name="topic" required="">
<option selected disabled hidden value="">Choose a Topic</option>
<option value="link">Site Link</option>
<option value="copyright">Copyright</option>
<option value="errors">Site/Article errors</option>
<option value="feedback">Feedback</option>
<option value="other">Other</option>
</select>
</div>
<div>
<label for="msg">Your message</label>
<textarea id="msg" name="user_message" required=""></textarea>
</div>
<div class="button">
<button type="submit">Submit</button>
</div>
</form>
And i wrote the javascript code below to change the default browser error message to the one below:
var inputName = document.getElementById('name');
var form = document.getElementById('form');
form.onsubmit = validateForm();
function validateForm() {
if(inputName.value === ""){
inputName.setCustomValidity("Name is required");
return false;
} else {
inputName.setCustomValidty("");
}
}
What am i doing incorrectly?
There were two issues in your JavaScript that were causing your validation to break:
The validateForm function was running on page load, rather than when the user submits the form. I've added in a revised event handler to resolve this
A spelling error was generating an error: setCustomValidty should be setCustomValidity
The following code fixes those issues.
HTML:
<form id="form" name="contactForm" method="post" action="php/formulario_contactos.php">
<div>
<label for="name">Your name</label>
<input type="text" id="name" name="name" required="">
</div>
<div>
<label for="mail">Your email</label>
<input type="email" id="mail" name="user_mail" required="">
</div>
<div>
<label for="topic">Select Topic</label>
<select id="topic" name="topic" required="">
<option selected disabled hidden value="">Choose a Topic</option>
<option value="link">Site Link</option>
<option value="copyright">Copyright</option>
<option value="errors">Site/Article errors</option>
<option value="feedback">Feedback</option>
<option value="other">Other</option>
</select>
</div>
<div>
<label for="msg">Your message</label>
<textarea id="msg" name="user_message" required=""></textarea>
</div>
<div class="button">
<button id="submit" type="submit">Submit</button>
</div>
</form>
JavaScript:
var inputName = document.getElementById('name');
var form = document.getElementById('form');
var submitButton = document.getElementById("submit");
submitButton.onclick = function () { validateForm(); };
function validateForm() {
if(inputName.value === ""){
inputName.setCustomValidity("Name is required");
return false;
} else {
inputName.setCustomValidity("");
}
}
I am not able to match the passwords, before Submit is clicked.
The submit goes even if the passwords are different.
var pass1 = document.getElementById('userPassword');
var pass2 = document.getElementById('userRepeatPassword');
function validatePassword(){
if (pass2.value == pass1.value) {
pass2.setCustomValidity('');
} else {
pass2.setCustomValidity('Both passwords do not match');
}
}
pass1.addEventListener('change', validatePassword);
pass2.addEventListener('keyup', validatePassword);
<form method="POST" action="login.php">
<div class="form-group">
<label for="inputFirstName">First name:</label>
<input type="text" class="form-control" name="firstName" id="inputFirstName" required>
</div>
<div class="form-group">
<label for="inputLastName">Last name:</label>
<input type="text" class="form-control" name="lastName" id="inputLastName" required>
</div>
<div class="form-group">
<label for="inputEmail">Email address:</label>
<input type="email" class="form-control" name="email" id="inputEmail" required>
</div>
<div class="form-group">
<label for="inputPassword">Password:</label>
<input type="password" class="form-control" name="userPassword" id="userPassword" required>
</div>
<div class="form-group">
<label for="inputRepeatPassword">Password repeat:</label>
<input type="password" class="form-control" name="userRepeatPassword" id="userRepeatPassword" required>
</div>
<div class="form-actions">
<button type="submit" class="btn btn-primary btn-block" style="background-color: #c2c2c2; color: black; font-weight: bold;">Submit</button>
</div>
</form>
It seems like I miss something, but I am not able to find it whole day already - any thoughts will be appreciated!
The validate should return the validation status and the form's onsubmit event handler should be able to react. Here's the sample:
var pass1 = document.getElementById('userPassword');
var pass2 = document.getElementById('userRepeatPassword');
function validatePassword() {
var status = false;
if (pass2.value == pass1.value) {
status = true;
pass2.setCustomValidity('');
} else {
pass2.setCustomValidity('Both passwords do not match');
}
return status;
}
pass1.addEventListener('change', validatePassword);
pass2.addEventListener('keyup', validatePassword);
<form method="POST" action="login.php" onsubmit="return validatePassword();">
<div class="form-group">
<label for="inputFirstName">First name:</label>
<input type="text" class="form-control" name="firstName" id="inputFirstName" required>
</div>
<div class="form-group">
<label for="inputLastName">Last name:</label>
<input type="text" class="form-control" name="lastName" id="inputLastName" required>
</div>
<div class="form-group">
<label for="inputEmail">Email address:</label>
<input type="email" class="form-control" name="email" id="inputEmail" required>
</div>
<div class="form-group">
<label for="inputPassword">Password:</label>
<input type="password" class="form-control" name="userPassword" id="userPassword" required>
</div>
<div class="form-group">
<label for="inputRepeatPassword">Password repeat:</label>
<input type="password" class="form-control" name="userRepeatPassword" id="userRepeatPassword" required>
</div>
<div class="form-actions">
<button type="submit" class="btn btn-primary btn-block" style="background-color: #c2c2c2; color: black; font-weight: bold;">Submit</button>
</div>
</form>
You have code to display if the passwords are the same or not. However, there is not any code to control how to handle submit with invalid passwords.
Here are two options:
1) <form onSubmit> as described in Pankaj's answer.
2) You could also have your validate function disable your submit button.
(Add an id to your submit <button type="submit" id=submitBtn class="btn btn-primary btn-block" style="background-color: #c2c2c2; color: black; font-weight: bold;">Submit</button>
function validatePassword(){
var submit = document.getElementById('submitBtn');
if (pass2.value == pass1.value) {
pass2.setCustomValidity('');
submit.disabled = false;
} else {
pass2.setCustomValidity('Both passwords do not match');
submit.disabled = true;
}
}
The had to be put in the bottom before the in order to work.