Jquery validator valid status with ajax submit - javascript

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/

Related

Jquery code to show modal after form validation is done

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..

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.

jQuery one function not working as expected

I have the following jsp:
...
<script type="text/javascript">
$(function() {
// prevent multiple submissions
$('#saveCallListBtn').one("click", function() {
$('#callListForm').submit();
});
});
...
</script>
...
<form:form id="callListForm" commandName="callList" action="${contextPath}/calllist/save" method="POST" htmlEscape="true">
...
<td colspan="2" style="text-align: center">
<input id="saveCallListBtn" type="submit" value="Save" class="button-med"/>
</td>
...
</form:form>
The behavior I am looking for is to only all the form to be submitted once no matter how many times the save button is clicked. Using the jQuery .one function, I can get the above code to correctly work. As the form will submit multiple times if I click more than once.
The following code will work fine:
$('#saveCallListBtn').on("click", function() {
$(this).prop("disabled", true);
$('#callListForm').submit();
});
But I am interested to know what I am doing wrong with the .one function.
Note the type here:
<input id="saveCallListBtn" type="submit" value="Save" class="button-med"/>
A submit button in a form will submit the form, no JavaScript required. So when your handler is automatically removed, on the next click the default handling (submitting the form) occurs, courtesy of the browser.
The only reason you're not seeing the form submitted twice on first click, I suspect, is that the act of submitting the form begins the process of tearing down the page to make room for the result of the submission.
FWIW, I would suggest that you not have a click handler on the button, but rather a submit handler on the form that, if all is well and it's going to allow submission to occur, disables the button and sets a flag to prevent future form submission, since forms can be submitted in multiple ways. (On some forms, pressing Enter in a text field will do it, for instance.)
E.g.:
$("#callListForm").on("submit", function(e) {
var $btn = $("#saveCallListBtn");
var valid = !$btn.prop("disabled");
if (valid) {
// ...do any other validity checks you may want, set `valid` to false
// if problems encountered...
}
if (valid) {
$btn.prop("disabled", true);
} else {
e.preventDefault();
}
});
The jQuery one function will execute the event handler only once. However, the default behaviour of the element clicked will execute indefinitely.
Change the type of the button to button, such that it has no default behaviour:
<input id="saveCallListBtn" type="button" value="Save" class="button-med"/>

JQuery Validate - Add/remove error css class in the form

I want to add/remove the error css class in the form.
$("#my-form").validate({
invalidHandler: function (event, validator) {
// 'this' refers to the form
var errors = validator.numberOfInvalids();
if (errors) {
$(this).addClass("error");
} else {
$(this).removeClass("error");
}
},
});
Problem with this approach:
When I use $("#my-form").validate().form() to validate the form, it will automatically add/remove the error css-class to each of the controls such as an input. By adding invalidHandler this additionally will add/remove the error css-class of the whole form.
Once I do validator.resetForm() to clear the messages, this will reset the css-class from the children controls but not from the form. I wish it automatically removes the css-class from the form by using a binding or any other sort of handler that trigger this action (removing the css-class from the form).
How I can fix this problem?
Source: http://jqueryvalidation.org/validate/
Update
Here a silly example: http://jsfiddle.net/F2Re4/ and I manually remove the class (in this example, I called the class: 'error-form')
Looking at the markup of your jsFiddle,
<input type="button" onclick="validate()" value="Validate"></input>
<input type="button" onclick="resetForm()" value="Reset Form"></input>
1) input elements do not have a closing tag. They may or may not need to be "self-closing" depending on your doctype, but there is never any such thing as an </input> tag.
2) Inline JavaScript is ugly and unnecessary when you use jQuery. onclick handlers can easily be removed and replaced with jQuery .on('click')...
$('#reset').on('click', function () {
var form = $("#myForm");
form.validate().resetForm();
});
3) You do not need a validate function attached to your "validate" button. Simply change the button into a type="submit" and it will be validated automatically. Otherwise, you would need another .on('click') handler and a .valid() within to trigger a validation test.
<input type="submit" id="validate" value="Validate" />
<input type="button" id="reset" value="Reset Form" />
Quote OP:
... validator.resetForm() to clear the messages, but this invalidHandler is never called and the 'error' css class still there in the form.
As per documenation, invalidHandler is only called when the form is invalid. If you reset the form, the form is no longer invalid. Therefore, the logic used within your invalidHandler is flawed.
var errors = validator.numberOfInvalids();
if (errors) {
$(this).addClass("form-error");
} else {
// this will never be called because invalidHandler
// is never called when there are no form errors
//$(this).removeClass("form-error");
}
There is nothing in this plugin that will automatically add/remove the class of the <form> element itself. The plugin only automatically adds/removes classes from the various data input elements. Therefore, if you manually add a class to the <form> element, then you're going to have to manually remove it when you reset the form.
$(document).ready(function () {
$("#myForm").validate({
// your rules & options
});
$('#reset').on('click', function () {
var form = $("#myForm");
form.validate().resetForm(); // reset validation on form
form.removeClass("form-error"); // remove error class from form
});
});
DEMO: http://jsfiddle.net/F2Re4/11/
Use .valid() to test the form. See the click function for valid()
validate = function(){
$("#myForm").valid();
};
resetForm = function(){
var form = $("#myForm").validate();
form.resetForm();
};
DEMO: http://jsfiddle.net/tive/U2XKx/
Additionally use reset() as seen on w3schools to clear the text value.

Calling Javascript on a form post to update UI via jQuery

I have an Input element that submits a form:
<input type="submit" value="Download" id="downloadButton" class="btn-download" />
I need the button to call a javascript function, and then post the form normally.
How would that be done in jQuery?
$('#downloadButton').on('click', function (e) {
e.preventDefault();
//call your function here
$(this).parents('form').submit();
});
the preventDefault() call is important because it stops the submission of the form so you can call your function before the form submit is called at the end.
You can do:
<form onsubmit="return doSomething();">
</form>
function doSomething() {
// do something
return true;
}
If in the doSomething function you don't like what you're seeing, then return false instead of true.
EDIT
The jQuery equivalent (to satisfy both commenters): remove the onsubmit from the HTML and replace with:
jQuery(document).ready(function () {
jQuery("form#myFormId").submit(doSomething);
});
Take a look at this jsfiddle
It changes the case of textbox content to to upper case before submitting the form
$('#formID').on('submit', function () {
//var form = $(this),
//input = form.find('input[type="text"]');
//input.val(input.val().toUpperCase());
//alert(input.val());
// call your function here!
});
this is what you request:
1.- click a button (adding event handler)
2.- call a function
3.- submit form
myfunction(){
//do wathever you want
$('#formid').submit();
}
$(document).on("click", "#downloadButton", myfunction);
you can do also:
$(document).on("click", "#downloadButton", function(event){
$('#formid').submit();
});
without having an extra function
but the solution of #Paritosh is the more accurate.
jsFiddle here
Change input type to type="button" and use:
$('#downloadButton').click(function() {
//Do any javascript stuff here
//And here, etc. Then, when ready...
$('#yourFormID').submit();
});
I recommend assigning an ID attribute to your form as it is good practice.
<form id="yourFormID" action="" method="POST">
Perhaps you have only one form on this page, in that case $('form').submit() is fine. But in future (or perhaps even on this page, you haven't said) you may have multiple forms on a page and therefore the ID is necessary to specify the exact form to be submitted.
Note that if you do NOT change the submit button element's <input type="submit" to <input type="button", then you must use e.preventDefault() to prevent the button's default action. Why bother with that? Just change type="button" and use less code and less future confusion.
add a submit event on form.
$('form').submit(function(event){
event.preventDefault();
var formObj = $(this);
var formData = formObj.serialize();
$.ajax({
type: 'post',
data: formData
}).done(function(response){
console.info(response);
// update UI here accordingly.
});
});

Categories