Can you call checkValidity() on a <form> element? - javascript

I was looking through the Constraint Validation API and found some example code online that seemed to call checkValidity() on <form> elements:
(function() {
'use strict';
window.addEventListener('load', function() {
var forms = document.getElementsByClassName('needs-validation');
var validation = Array.prototype.filter.call(forms, function(form) {
form.addEventListener('submit', function(event) {
if (form.checkValidity() === false) {
event.preventDefault();
event.stopPropagation();
}
form.classList.add('was-validated');
}, false);
});
}, false);
})();
But I tried to do this myself and it didn't work. I couldn't find any reference to this being possible anywhere else either. As far as I figured, it can't be called on <form>. Could someone help me out?

You are using submit , but if you are using input there is no submit event for it. You can use input or paste event handler for input
window.addEventListener('load', function() {
var forms = document.getElementsByClassName('needs-validation');
var validation = Array.prototype.filter.call(forms, function(form) {
form.addEventListener('input', function(event) {
if (form.checkValidity() === false) {
event.preventDefault();
event.stopPropagation();
}
form.classList.add('was-validated');
}, false);
});
}, false);
<form>
<input type='email' class='needs-validation'>
<button type='submit'>Submit</button>
</form>

Actually there are many ways to dot this.
It seems like you have written a self-invoking JS function.
In the other simple way, you can simply write a onsubmit event attribute in tag and write the function name.
e.g.
<form onsubmit="return checkValidity()">
//...rest stuff
</form>
Based on the returned result from the function, whether true or false depending on the conditions the form will get submitted or stop submission respectively.

Related

Form still submits, trying to use e.preventDefault();

So I have this form. I want to check if user has validaty the captcha, but have problems. Here is the form, that checks the function.
<form data-id="embedded_signup:form" id="myForm" class="ctct-custom-form Form" name="embedded_signup" method="POST" action="https://visitor2.constantcontact.com/api/signup" onsubmit="check_if_capcha_is_filled()">
Here is the function that determines whether doSubmit (the captcha) has been validated.
function check_if_capcha_is_filled(e){
if(doSubmit) return true;
e.preventDefault();
alert('Fill in the capcha!');
return false;
};
But I get an error
Uncaught TypeError: Cannot read property 'preventDefault' of undefined
at check_if_capcha_is_filled
Any pointers to what I am missing? Thank you.
Your e.preventDefault is being used incorrectly. It will do nothing because you're passing an event to a function, you want to attach it to the event handler like this:
$('form').on('submit', function(e)
{
e.preventDefault();
//rest of code
})
this will stop the submit action.
refs: http://api.jquery.com/event.preventDefault/
Is this what you want?
<form data-id="embedded_signup:form" id="myForm" class="ctct-custom-form Form" name="embedded_signup" method="POST" action="https://visitor2.constantcontact.com/api/signup">
Then in your js file:
function check_if_capcha_is_filled(){
if (doSubmit){
return true;
}else{
return false;
}
};
$('#myForm').on('submit', function(e){
if (!check_if_capcha_is_filled){
e.preventDefault();
}
});
You have two issues here. Firstly you need to return the function from the onsubmit event attriubute. Secondly, you're not passing the event in to the function - however this will only work where a global event is available, ie. not Firefox.
To fix the issue, and improve your logic, you can instead use addEventListener() to unobtrusively add the event handler to the element, and remove the outdated on* event attribute. Try this:
var doSubmit = false;
document.getElementById('myForm').addEventListener('submit', function(e) {
if (doSubmit)
return;
e.preventDefault();
alert('Fill in the capcha!');
});
<form data-id="embedded_signup:form" id="myForm" class="ctct-custom-form Form" name="embedded_signup" method="POST" action="https://visitor2.constantcontact.com/api/signup">
<button type="submit">Submit</button>
<form>
Use on event listener
change it to
<form data-id="embedded_signup:form" id="myForm" class="ctct-custom-form Form" name="embedded_signup" method="POST" action="https://visitor2.constantcontact.com/api/signup" >
$('form').on('submit', function(e){
// validation code here
if(!valid) {
e.preventDefault();
}
});
Using jQuery and if you want to confirm the submit.
<button name="delete" class="submitbutton">Delete</button>
$('.submitbutton').click(function() {
var buttonpressed;
buttonpressed = $(this).attr('name');
var r = confirm("Please confirm to " + buttonpressed );
if (r == true) {
$('#yourformid').submit();
} else {
return (false);
}
});

Adding Google Analytics event to form submit

I'm looking to add a Google Analytics event to a form that I can not access the inline html, so I can not add it as a onClick="" event straight to the html.
So my solution has been so far:
$(function() {
$(".form_submit input").on("click", function() {
dataLayer.push({
"event": "Kontakt",
"eventCategory": "Submit",
"eventAction": "Kirjuta meile",
"eventLabel": "Kirjuta meile"
});
});
});
Althought this does not seem to work as clicking the submit button possibly stops all functions and refreshes the page.
How can I run the function before submit and then submit the form after? I've been suggested using preventDefault(); and the after calling the submit again with $('form').one('submit', ... but have been unable to implement this due to lack of skill.
View site: http://avrame.com/en (the form is at the bottom of the page)
Any suggestions appreciated.
You can actually push functions to dataLayer, and it will be executed after the first event.
I would do
delegate the submit watch event to document level (see Jquery .on() submit event)
intercept the first submit, pushing event and preventing default behavior
and insert a function inside dataLayer, which submits the form again, but this time it won't be halted
The code:
window.submitGA = false;
$(function() {
$(document).on('submit','.form_submit',function(event){
if (!window.submitGA)
{
window.submitGA = true;
dataLayer.push({
"event": "Kontakt",
"eventCategory": "Submit",
"eventAction": "Kirjuta meile",
"eventLabel": "Kirjuta meile"
});
dataLayer.push(function(){
$('.form_submit').submit();
});
event.preventDefault();
}
});
});
Working solution ended up using this callback method:
var form = document.getElementsByClassName('.footer__contact form');
form.addEventListener('submit', function(event) {
event.preventDefault();
setTimeout(submitForm, 1000);
var formSubmitted = false;
function submitForm() {
if (!formSubmitted) {
formSubmitted = true;
form.submit();
}
}
ga('send', 'event', 'submit', 'Saada', 'Kirjuta meile', {
hitCallback: submitForm
});
});
Reference from: https://developers.google.com/analytics/devguides/collection/analyticsjs/sending-hits#hitcallback

off() not working in firefox but working in chrome

I am using a beforeonload function but I want when the user submits the form beforeunload shouldn't work. Here is my code, which works fine in Chrome but not in Firefox.
window.form_submitted = '';
jQuery(document).ready(function() {
jQuery(window).on('beforeunload', function() {
if (form_submitted == '') {
return "Are you sure to leave that page";
}
});
});
jQuery('#form').on('submit', function (e) {
e.preventDefault();
jQuery(window).off('beforeunload');
form_submitted = 1;
site_redirect(resp.payment_url);
}
return false;
});
You have several syntax issues, and you have to place the submit block inside the DOMReady handler, otherwise JS will attempt to bind the event to an element which doesn't yet exist in the DOM. Also note you can remove the the global flag variable as you are unbinding the beforeunload event on form submission. Try this:
jQuery(document).ready(function($) {
$(window).on('beforeunload', function() {
return "Are you sure to leave that page";
});
$('#form').on('submit', function (e) {
e.preventDefault();
$(window).off('beforeunload');
site_redirect(resp.payment_url);
});
});
Also note that by doing a redirect when the form is submit (assuming that's what the site_redirect function is doing) then the content of the form will be lost.

How to add a selector for a form submit, only if specific button type caused the form submission

I have the following code:
$(document).ready(function () {
$('body').on("submit", "form", function () {
$(this).find('.btn-primary').prop("disabled", "disabled");
$('#progress').show();
});
$('body').on("change", "form", function () {
$('.btn.btn-primary').prop("disabled", false);
$('#progress').hide();
});
});
But how I can force the script to fire only if a button that have .btn.btn-primary caused the form to submit, while if I submit the form using for example button of class .btn.btn-default to not fire the above script?
EDIT
I tried this but now the script will never fire:
$(document).ready(function () {
$(document).on("submit", "form", function () {
//^^ use document instead of body
//check if button has btn.btn-default class and if exist return
if($('button').hasClass('btn.btn-default')){
return;
}
$(this).find('.btn-primary').prop("disabled", "disabled");
$('#progress').show();
});
$(document).on("submit", "form", function () {
//$('form').change(function () {
$('.btn.btn-primary').prop("disabled", false);
$('#progress').hide();
});
});
You can return the form if button has class using hasClass
$(document).on("submit", "form", function () {
//^^ use document instead of body
//check if button has btn.btn-default class and if exist return
if($('button').hasClass('btn.btn-default'){
return;
}
$(this).find('.btn-primary').prop("disabled", "disabled");
$('#progress').show();
});
You are testing for multiple combined classes, so you must separate the classes in hasClass with a space (not the dot):
// if the button has both classes
if($('button').hasClass('btn btn-default')){
return;
}
e.g. text example: http://jsfiddle.net/80001ra0/

Using click event while button is disabled

I need to check on clicks while the button is disabled is this possible? Or is there any other way to this?
HTML:
<form id="form">
<input type="submit" id="submit" value="Submit" />
</form>
JS:
$("#form").submit(function (e) {
e.preventDefault();
return false;
$("#submit").on("click", function () {
alert("Bla");
});
});
JS Fiddle: http://jsfiddle.net/hjYeR/1/
When you are using preventDefault(), there is no need to use return false.
However, any code after return statement in a function, won't execute.
Also there is no need to attach an event inside another event, write them separately:
$("#form").submit(function (e) {
e.preventDefault();
});
$("#submit").on("click", function () {
alert("Bla");
});
jsFiddle Demo
After you return false; the rest of your function will not run. You can bind your click event before returning false and it should work.
return statements are the end point in the function, the codes will not proceed ahead of that.
What you can do is simply remove the click event handler from within the submit handler itself.
$("#form").submit(function (e) {
return false; //e.preventDefault(); is not needed when used return false;
});
$("#submit").on("click", function () {
alert("Bla");
});

Categories