Jquery code to show modal after form validation is done - javascript

Following on from this question: Previous question
I have form validation on my form, which needs to be validated first i.e minimum characters and numbers etc.
My Jquery code so far shows the modal after the submit button is pressed and the form has some input in there but not the valid input, so I just need to type a few characters and the modal pops up which is not ideal.
So I need the form to have input and validate then the modal pops up and the user has to accept terms and conditions then they can register.
I have tried the following with no luck:
$(document).ready(function() {
$("#login-form").submit.valid(function(e) {
e.preventDefault();
$(".modal").addClass("active");
});
});
Thanks in advance

You should use an if inside your submit event:
$("#login-form").submit(function(e) {
e.preventDefault();
if ($(this).valid()) { // this assumes you are using something like jquery validate - from your original code, it looks like you were attempting to do this
$(".modal").addClass("active");
} else {
// do error stuff here
}
});

Why use valid? jQuery valid() does not accept any arguments, only returns true. Use validate() instead to use handler.
$("#yourform").validate({
submitHandler: function(form) {
// ...
form.submit();
}
});

you can do this on your form...
<form id="myform" action=".." method=".." onsubmit="return validateForm(this);">
.....
</form>
then in your script you define the validate(this) function which receives the form object(this).
now lets assume you are using the jquery form validation plugin
function validate(formObj){
v = $(formObj).validate({ // initialize the plugin
rules: { //enter additional rules.
input1: {required: true, email:true},
input2: {required: true, integer:true}
},
submitHandler: function(formObj) {
$('#myform').removeAttr('onsubmit'); //remove the onsubmit attr..
$(modal).addClass('active'); //then show the modal here..
}
});
return false; //which stops the form from submitting..
}
now lets assume the modal has popped up and the user has accepted the agreement and clicked on the agree button, which then triggers the form and sends it
function sendFromModal(){
$('#myform').submit();
return true; //
}
this should work, i hope i was helpful enough..

Related

Why doesn't my statement to disable form submission work?

I have a checkout form on my website that uses a custom validation method implemented with Bootstrap. It has a JavaScript function to prevent the form from being submitted multiple times if it is filled out correctly. I'm using a technique commonly suggested on SO to disable the submission, albeit with vanilla JavaScript instead of JQuery. This is the function:
function submitForm() {
// Fetch all the forms we want to apply custom Bootstrap validation styles to
var forms = document.getElementsByClassName('needs-validation');
// Loop over them and prevent submission
var validation = Array.prototype.filter.call(forms, function(thisForm) {
event.preventDefault();
if (thisForm.checkValidity() === false) {
event.stopPropagation();
}
thisForm.classList.add('was-validated');
<?php if(isset($shipping)){
echo "stripe.createToken(card).then(function(result) {
if (result.error) {
// Inform the user if there was an error
} else {
thisForm.addEventListener('submit', function(event){
event.preventDefault();
return false;
});
// Send the token to the server
console.log('Sending token ' + result.token + '.');
}
});";
}?>
});
};
The form is created like this:
<form id="payment-form" onsubmit="return submitForm()" class="needs-validation" novalidate>
When I test the page with the form filled out correctly, double clicking the submit button prints the "Sending token" message to the console twice when it should only happen once. I thought maybe it was because it was taking too long to get to the part of the function where the form is disabled, but the message prints again no matter how many times the button is clicked.
Using inline event handlers is bad practice and results in poorly factored, hard-to-manage code. Seriously consider attaching your events with JavaScript, instead, eg: https://developer.mozilla.org/en/DOM/element.addEventListener
You're not calling the validation function with the event of when the form was clicked - and then you reference event.preventDefault();, but event is not defined.
Try something like this instead. Remove the onsubmit attribute, and do:
[...document.querySelectorAll('.needs-validation')].forEach((thisForm) => {
thisForm.addEventListener('submit', (event) => { // add the event argument here
event.preventDefault();
if (thisForm.checkValidity() === false) {
// rest of your code
(though, I don't see why you're using .filter in the first place it doesn't make sense here - did you mean to use forEach? And if there's only one #payment-form, couldn't you have selected that by itself?)
To stop a form from submitting you should call event.preventDefault() or return false;
<form onsubmit="handleSubmit"></form>
handlesubmit(event) {
event.preventDefault();
// or return false;
}

Parlsey prevent keydown validation after initial validation call

I am validating a form using Parlsey like so:
$(document).on("click", ".submit-form-btn", function(e) {
$(".form-class").off().submit(function(e) {
e.preventDefault();
$(this).parsley().validate();
if ($(this).parsley().isValid()) {
//Do something
}
});
});
After the initial validation, validation checks appear to be calling on every "keydown" press. How can I only validate again when my ".submit-form-btn" is clicked on again? I only want validation checks on click.
You can achieve this by adding the data-parsley-trigger-after-failure attribute with a value of submit. This will then ensure only submits will trigger further validation. You can either add it to individual fields (causing some fields to continue to validate on input while others will only validate on submit), or to the entire form (to specify submit-only validation everywhere):
<form id="form" data-parsley-trigger-after-failure="submit">
or:
<input type="text" required data-parsley-trigger-after-failure="submit">
Here's a Codepen example.

Jquery validator valid status with ajax submit

I am trying to post a form using ajax after a form has been validated. However the .valid seems to be wrong.
Multiple action type is desired based on button.
This example is also not showing the errors messages correctly upon submit
$('#submit').click( function(){
alert(validator.valid());
});
$('#submit2').click( function(){
alert(validator.valid());
//do something else
});
status become true if i enter a required field (e.g name)
this is the fiddle
try this fiddle
http://jsfiddle.net/r2HUu/4/
It's working. I just checked form' validation by $("#myForm").valid()
Quote OP:
"I am trying to post a form using ajax after a form has been validated"
As per documentation, your ajax goes inside the submitHandler callback function.
submitHandler (default: native form submit) Type: Function()Callback
for handling the actual submit when the form is valid. Gets the form
as the only argument. Replaces the default submit. The right place to
submit a form via Ajax after it validated.
Using this callback, the click is captured automatically and the function is only fired on a valid form.
$(function () {
var validator = $("#myForm").validate({
// rules and options,
submitHandler: function(form) {
// your ajax goes here
alert("valid form");
return false;
}
});
});
DEMO: http://jsfiddle.net/fXDwd/
Quote OP:
"However the .valid seems to be wrong."
EDIT
As per OP's comments and updated jsFiddle:
If you want to have multiple submit buttons do different things on one form, construct click handlers for each button which you've already done. Now you must move those buttons to outside of the <form></form> container. Otherwise, the plugin will treat them both as normal submit buttons and interfere with your click handlers.
The other problem is your implementation of .valid(). Attach it to the form element, $("#myForm"), not the validator initialization object.
HTML:
<form id="myForm" action="">
...
</form>
<input type="button" id="submit" value="Submit form" />
<input type="button" id="submit2" value="Submit form2" />
jQuery:
$(function () {
var validator = $("#myForm").validate({
// rules and options
});
$('#submit').click(function () {
alert($("#myForm").valid());
//do something
});
$('#submit2').click(function () {
alert($("#myForm").valid());
//do something else
});
});
DEMO: http://jsfiddle.net/vfrGU/

Form validation in javascript does not work probably

I am working on this form which is suppose to validate the form before submitting
$(document).ready(function() {
$("#form3").validate();
if ($('#form3').valid()) $('#form3').submit();
});
But the problem is: it prints the (empty fields error) when the form is loaded.
UPDATE : the function is now working Horraaay :) with the following code:
<script>
$(document).ready(function(){
$("#form3").validate();
});
</script>
The only problem was the input form name .. I used 'submit' as a name of the input form however before was on different name.
Put your code on the form submit event. Something like this:
$(document).ready(function()
{
$("#form3").validate();
$("#form3").submit(function(event)
{
if (!$(this).valid())
{
event.preventDefault();
}
});
});
I think by default after successful validation it will submit the form . However i don't know why you need to resubmit the form.
If you need to submit manually you can use the SubmitHandler place to submit your form.
$("#form3").validate({
submitHandler: function(form) {
form.submit();
}
});
I solved the problem and now it works ...
It is a minor error !
I changed the submit button name and id to ( Submit).

Preventing a form from submitting in jQuery Validate plugin's submitHandler function

I am using jQuery with the validate plugin at http://docs.jquery.com/Plugins/Validation/validate
I want to prevent the form from submitting after its validation and submission processes done via ajax.
I have the following code:
$("#myform").validate({
rules: {...},
submitHandler: function(form) {
alert("Do some stuff...");
//submit via ajax
return false; //This doesn't prevent the form from submitting.
}
});
However, the problem with this is that the submitHandler submits the form even though I have a return false; statement at the last line of the handling function. I want prevent the default behaviour and to stop the form from submitting because I have already submitted via ajax.
How should I stop the code from submitting after going through the ajax codes in the submitHandler function?
I do it like this and it works exactly how you want it to work:
$("#myform").submit(function(e) {
e.preventDefault();
}).validate({
rules: {...},
submitHandler: function(form) {
alert("Do some stuff...");
//submit via ajax
return false; //This doesn't prevent the form from submitting.
}
});
$("#myform").validate({
rules: {...},
submitHandler: function(form, event) {
event.preventDefault();
alert("Do some stuff...");
//submit via ajax
}
});
Hope this help.
working fiddle
according to jquery plugin validation document.
submitHandler (default: native form submit)
the submission method via submitHandler below is quoted from documentation it should work , but it actually does not work they said that
Callback for handling the actual submit when the form is valid. Gets the form and the submit event as the only arguments. Replaces the default submit. The right place to submit a form via Ajax after it is validated.
Example: Submits the form via Ajax, using jQuery Form plugin, when valid.
$("#myform").validate({
submitHandler: function(form,event) {
event.preventDefault();
$(form).ajaxSubmit();
}
});
i am writing code here what worked for me.
simply call your validayion plugin , and donot include submitHandler in your validation function arguments.
instead of submitting and preventing with submitHandler use jQuery method of form submission. like below
$("form").validate({});
$(document).on("submit", "form", function (event) {
event.preventDefault();
alert("submit");
});
Maybe you can validate externally without using a submit button:
if($("#myform").valid()){
alert("Do some stuff...");
}
You can call event.preventDefault() on submit event:
$("#myform").on("submit", function(event) {
event.preventDefault();
});
You can code this in a very simple way via "jQuery Walidate".
http://jquery.dop-trois.org/walidate/
There you can code a function, that will be executed on submit.
Look for Callback in the Documentation.
unfortunately it seems that the call: submitHandler: function(form){ does not take an event argument so it seems that the only solution is a return false statement like this:
...
submitHandler: function(form) {
//your code
return false;
},
...
I fixed this way. A patch for a jQuery Validation Plugin bug that it's not fixed even on v1.19.0
$('#save_edit_user').on('click', function () {
var isValid = $("#edit_user").validate().form() && $("#edit_user").validate().element("#edit_user_email");
//check current ajax call by $.active
//the form is not submitted before 0 ajax is running
if (isValid && $.active == 0){
// my save logic
}
});

Categories