Parlsey prevent keydown validation after initial validation call - javascript

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.

Related

Submit form with jquery which has multiple submit buttons without click trigger?

Imagine this :
<form id="form">
<input type="text">
<button type="submit" name="submit1" value="1">something1</button>
<button type="submit" name="submit2" value="2">something2</button>
<button type="submit" name="submit3" value="3">something3</button>
</form>
First of all when I write $('#form').submit() which submit value will be sent? the first one?
Second of all How can I submit the form without the click trigger event with the value I want? Is it possible at all? For example submitting the form with the 2 submit value.
The reason I want do this is to have confirmation popup with sweetalert before sending my form so here it is :
$('form').on('submit',function(e){
form = $(this);
e.preventDefault();
swal({'some dialog'},function(isConfirm)
{
if(isConfirm)
form.submit;
\\If I use the click trigger I will get stuck in here again.
})
});
There is an alternative - use the FormData You can create an instance of a FormData, add your html form, modify entries, and send it. Everything is under your control here then.
EDIT: Based on your edit, it seems you have the problem of resubmitting the form. You can handle it like this.
var form = document.querySelector('form');
form.addEventListener('submit', {
confirmed: false,
handleEvent: function (event) {
if (this.confirmed)
return;
event.preventDefault();
doconfirm((confirmed) => {
if (confirmed) {
this.confirmed = true;
form.submit();
}
})
}
}, false);
Or you can solve your problem by unbinding the submit handlers after validation and submit it again: $('form').off('submit').submit()
As #Scott Marcus explained, the value of named buttons will be submitted when the form is sent to the server. However in your case, this won't help because you want to perform some logic before submitting it to the server.
The issue is that jQuery has no way to determine which button was clicked because it doesn't provide the submit button values when you look at the form data via $.serialize(), and there is no easy cross-browser friendly way to check the button that triggered the $.submit() event without using click.
So, the only workaround would be to handle the click event of the 3 buttons and store some value that is checked before you submit the form as described in this answer: How can I get the button that caused the submit from the form submit event?
Example: http://codeply.com/go/Wj85swRyfX
Let's take your questions one at a time...
First of all when I write $('#form').submit() which submit value will
be sent? the first one?
When a form is submitted, ALL form elements that nave a NAME attribute will submit their value (even if the value is an empty string) to the form's ACTION destination. So, in your case, all 3 of your buttons have a name attribute and so all 3 buttons will submit their name/value pairs.
Usually, we don't put a name attribute on the submit button because we only want it to trigger the submit, not actually use it as a data container. And, we usually include only a single submit button under most circumstances.
Second of all How can I submit the form without the click trigger
event with the value I want? Is it possible at all? For example
submitting the form with the 2 submit value
You would use:
$('#form').submit()
to manually cause the submit, but you'd need to have an if() statement that has logic that determines which value is appropriate to submit. Instead of the value being stored in a button, you could use a hidden form field, like this:
<form id="form">
<input type="text">
<input type="hidden" name="hidden" value="">
<button type="submit">something3</button>
</form>
JavaScript:
$("#form").on("submit", function(evt){
// Stop the form submission process
evt.preventDefault();
// Logic that sets hidden input field to correct value:
if(condition1){
$("input[type=hidden]").attr("value", "1");
} else if(condition2) {
$("input[type=hidden]").attr("value","2");
} else {
$("input[type=hidden]").attr("value","3");
}
// Manually submit the form
$("#form").submit();
});
I suggest to use hidden input tag to make the logic clear.

re-enable an input after it was disabled through javascript because it was empty

I am using jQuery Validator to validate a form and I wanted to disable the fields that were blank when the user clicks submit so that the server does not receive any data from the inputs that were left blank. To disable them, I used the following Javascript:
$(function() {
$("#form1").submit(function() {
$(this).find(":input").filter(function(){ return !this.value; }).attr("disabled", "disabled");
return true; // ensure form still submits
});
});
Here is my problem: This code works great assuming the form was validated on the first submission. However, if the user hits submit but it was not validated, all of the alerts for various required fields and such pop-up, but all of the inputs are disabled. How can I fix this? I need to know how to re-enable them if the form is not validated and properly submitted.
It doesn't make sense to disable the field to submit. Rather—you should first do a front-end only validation that prevents submitting if there are empty fields (and those fields are required to not be empty).
You can set up a variable (or a function) to run through your validation and only submit if it returns true. This is a condensed example of just one input.
var validate = ($('input').val() == '') ? false : true;
if(validate){
// submit your form
} else {
// throw your errors
}
Then it would be good to clear your errors at the beginning of your validation.

parsley.js - disable the maxlength validation

I am trying to dynamically disable the parsley.js max length on several of my input fields when the user makes a selection on a select list on the form.
I have read this thread, but when I put the code into my field, the parsley is not triggered, instead the form submits, and I do not understand why.
I have read the parsley.js docs, but I am unable to see why the parsley.js validation is ignored when i add the following line of code:
$('#id_employment_record_position_title').attr('data-parsley-maxlength', '0');
or
$('#id_employment_record_position_title').attr('data-parsley-maxlength', '150');
This is my code to dynamically turm the parsley validation on and off when the user changes the select list on the form:
function toggleFormDetails() {
if ( $('#id_employment_record_display_type').val() == '8888' || $('#id_employment_record_display_type').val() == '9999' ) {
//disable the input field.
$('#id_employment_record_position_title').prop('disabled', true);
....
//destroy parsley on the form.
//$('#employment_history_details_form').parsley().destroy();
//disable the parsley maxlength, when the input field is disabled.
$('#id_employment_record_position_title').attr('data-parsley-maxlength', '0');
//reinitialise parsley on the form.
//$('#employment_history_details_form').parsley();
} else {
//enable the input field.
$('#id_employment_record_position_title').prop('disabled', false);
....
//destroy parsley on the form.
//$('#employment_history_details_form').parsley().destroy();
//change the parsley cs error values for all the required form inputs.
$('#id_employment_record_position_title').attr('data-parsley-maxlength', '150');
//reinitialise parsley on the form.
//$('#employment_history_details_form').parsley();
}
}
Why do I have have to add the destroy & create parsley code on the form (I have commented them out above)?
Would it be better to write a custom validation for this? If so, how would I do that, b/c my js code skills are not yet good enough?
Parsley is a Javascript library and works something like this:
When you render your html form, you specify the needed validations through data attributes.
You indicate that the form will be validated by Parsley either with the form attribute data-parsley-validate or via javascript through $("#form").parsley().
When parsley is binded to your form (the second step), an object of the type ParsleyForm will be created containing the constraints for each field.
After the object is created, the html attributes are no longer needed. So, if you change any attribute it will have no impact on the validation since Parsley will verify the constraints of the javascript object. This is why you need to destroy & bind parsley (in order to recreate the parsley instance with the new constraints).
In order to solve your issue, you could do something like this:
<form id="myForm" class="form-horizontal" method="post">
<input type="text" name="id_employment_record_display_type"
id="id_employment_record_display_type"
placeholder="Set 8888 to discard maxlength validation" />
<input type="text" name="sample" id="id_employment_record_position_title"
data-parsley-maxlength="150" />
<button type="submit">Submit</button>
</form>
<script>
$(document).ready(function() {
$("#myForm").parsley();
$("#id_employment_record_display_type").on('change', function() {
$("#myForm").parsley().destroy();
if ( $(this).val() == '8888' || $(this).val() == '9999' ) {
$('#id_employment_record_position_title').removeAttr('data-parsley-maxlength');
$('#id_employment_record_position_title').prop('disabled', true);
} else {
$('#id_employment_record_position_title').attr('data-parsley-maxlength', '150');
$('#id_employment_record_position_title').prop('disabled', false);
}
$("#myForm").parsley();
});
$("#myForm").submit(function() {
$(this).parsley().validate();
// when there are no client side errors when the form is submitted
if ($(this).parsley().isValid()) {
console.log('no client side errors!');
} else {
console.log('form is not valid');
}
event.preventDefault();
});
});
</script>
You can also check this working jsfiddle

Bootstrap form input: prevent submit, but allow for input checking

I've got the following problem:
I use bootstrap form to take input from users, and I use jQuery preventDefault() to disable the submit button from sending the form (I use AJAX instead). However, that function also prevents input checking that is done by bootstrap. For example, if someone enters an e-mail without '#' into
<input type="email" class="form-control">
bootstrap would, upon clicking submit, check that input and return a popup with an error.
My question is: how to prevent the request being sent while keeping the bootstrap form checking mechanism intact?
What I have tried: using preventDefault() and writing my own checking script, however this seems like reinventing the wheel and having extra code when it's not needed.
Thank you!
I believe you are talking about the native HTML5 form validation and not validation by bootstrap its self, I have never come across bootstrap validation before. (i may be wrong though).
Most new browsers will validate <input type='email'/> as an email address and <input type='text' required='required'/> as required on form submission.
If for example you are using e.preventDefault(); on the click event on the submit button the form will never attempt to submit and hence the native validation will never happen.
If you want to keep the validation you need to use e.preventDefault(); on the submit event of the form not the click event on the button.
The html...
<form action='' method='post'>
<input type='email' name='email' required='required' placeholder='email'/>
<button type='submit'>Submit</button>
</form>
The jQuery...
//this will stop the click on the button and will not trigger validation as the submit event will never be triggered
$("button").on('click',function(e){
e.preventDefault();
//ajax code here
});
//this will stop the submit of the form but allow the native HTML5 validation (which is what i believe you are after)
$("form").on('submit',function(e){
e.preventDefault();
//ajax code here
});
Anyway hope this helps. If I have misunderstood in any way let me know and ill try to assist further.
I had the same issue, I came to use "stopPropagation" as the way to stop the form submission. But after a little reading on jQuery 3, I realized that "preventDefault" was enough to what I wanted.
This caused the form validation to happen and the submit event didn't proceed.
(This example is of an attempt i had on my own).
$('form').on("submit",function( event ) {
if ( $('#id_inputBox_username').val().length == 0 &&
$('#id_inputBox_password').val().length == 0 ) {
event.preventDefault();
$('#id_inputBox_username').tooltip('show');
$('#id_inputBox_password').tooltip('show');
} else if ( $('#id_inputBox_username').val().length == 0 ) {
event.stopPropagation();
$('#id_inputBox_username').tooltip('show');
} else if ( $('#id_inputBox_password').val().length == 0 ) {
event.stopPropagation();
$('#id_inputBox_password').tooltip('show');
}
});
I had the same problem and I find this solution:
$('#formulario').on('submit', function (e) {
if (e.isDefaultPrevented()) {
// handle the invalid form...
} else {
// everything looks good!
e.preventDefault(); //prevent submit
$(".imprimir").show();
$(".informacao").fadeOut();
carregardados();
}
})

Parsley.js validation

As an exercise I have added some parsley validation to this form here
http://matthewpiatetsky.com/cs401/login.html
I am now trying to add a similar validation to the form here
http://matthewpiatetsky.com/cs401/writereviews.html
(I have some mouseout validation on the text area)
I am running into two issues:
How can I get the form to validate before the form submits to its action? Can I run validation first, and if validation succeeds, then submit the form.
How can I add data-required="true" to the jquery raty stars to force the user to fill those in?
Thanks!
For validation before submit you can do something like:
var form = document.getElementById(“yourFormID”);
form.addEventListener("submit", function(event) {
// do your additional validation here
if (something wrong)
event.preventDefault();
}, false);

Categories