I want to perform javascript validation after user submits the form. Documentation for jQuery .submit() clearly says:
The submit event is sent to an element when the user is attempting to submit a form.
But if I put
$('form.simple_form.new-channel').submit perform_validation()
into my code, perform_validation() is triggered every time page is rendered! Even when there is no form on it and no 'submit' button. What is the correct way to call a function after submitting a form?
I believe You dont want to trigger action after submitting, You just want to run it after user clicks submit button.
Wouldn`t it work put like that?
$('form.simple_form.new-channel').submit(function(e){
if(!perform_validation()){
e.preventDefault(); //prevents form from being submitted if validation fails
return; //exits function
}
})
Your perform_validation function should then return Boolean value.
EDIT:
You wrote Your function like this:
$('form.simple_form.new-channel').submit perform_validation()
which is exact the same as writing:
$('form.simple_form.new-channel').submit;
perform_validation();
In Your version script just runs the perform_validation() because it isn`t inside event handler.
You could also do it this way:
$('form.simple_form.new-channel').submit(perform_validation);
This one tells the script to run on the form submit, the function which name is passed as an argument.
The problem is your syntax.
$('form.simple_form.new-channel').submit perform_validation()
Because of javascript's liberality the fact that you are not invoking submit here and you have no semicolin after perform_validation... causes no error, but simply invokes perform validation as if it was on the line all by its self with a semicolin.
to correct this, do this
$('form.simple_form.new-channel').submit(perform_validation);
Related
I am placing my HTML form inside of another system and cannot get my own function to run during the submit event.
I cannot use Form onSubmit='foo' as the system has a script that automatically populates the onSubmit of any form placed inside of it (overwriting anything placed beforehand).
Additionally, this system has its own validation that it performs at the submit event.
So I am trying to use the EventListener to run my function as well as the system one at form submission, however it is not working. The console.log doesn't even show up.
I see that the system function has:
document.forms[0].submit();
So it must be firing before my function causing mine to never run as the system function either submits or cancels the submit it appears.
Here is my eventListener code.
var formRef = document.forms.myForm;
myForm.addEventListener('submit', function(evt) {
evt.preventDefault();
console.log('event fired');
//checkBlanks function loops through the form looking for blanks,
//if a field is blank it changes it to red and then fires the system's
//confirmation dialogue. Else it fires the system's confirmation dialogue.
checkBlanks();
});
In the event that it matters, my form is inside of the system's form and the submit button is located in the system's portion of the window. I tried to addEventListener the button but it says it cannot get property of undefined reference.
All you need to do is to call the form tag or you call an #id to it
enter code here
document.querySelector('form').addEventListener('submit',execute);
function execute(e){
console.log('submitting...');
e.preventDefault();
}
We are currently binding to the click event of a submit button (there are reasons why we are not binding to the submit event for the form). Is it guaranteed that our JS will run before the form submits (as we are entering values into hidden fields that we want to submit) or do we need to prevent the form from submitting and then call the submit again?
$(function() {
$('#button').on('click', function() {
// Do some stuff here - needs to finish before the form submits
return true;
});
});
Thanks in advance!
It will work before the submit event is sent, but you are only listening for the click event. If the user hits enter, the form will be submitted without running your code. I think you should stick to the submit event. The callback function will receive as argument the event (and you can do things like e.preventDefault(); or e.stopPropagation();
$("form").on("submit",function(event){});
In my expierience the code in the click event will always run first.
I just ran a simple test on latest chrome with a loop that loops 10,000 times. The form did not submit until after the loop was finished (~5 seconds).
If you try to run some ajax call, or setTimeout in the click function though, the form will most likely submit before your callback/ajax is finished.
I have ajax calls made like this:
$('.register a').click(register);
The register function:
function register(e){
e.preventDefault();
var params = $('.register').serialize();
Api.callApi(
"/api/authkey/create_user",
params,
//success!
function(response){
settooltip(response.msg[0])
// GA
_gaq.push(['_trackPageview', '/registered']);
_gaq.push(['_trackEvent', 'register', 'public']);
},
//error
function(response){
settooltip(response.msg[0])
}
);
}
Sometimes ajax responds with errors. I try to show theese arrows next the field that has the error(that's what the settooltipc–function does). However, the api only responds with the name of the field that has the error, and sometimes, there are more fields than one with the same name. This means I can't know what field I should apply the error message to.
My Idea for how to solve this is by setting an ID to the form that was latest submitted. However, I would like to do this within the register-function. I could use "this" if someone actually clicks the .register a, but if they use enter, "this" contain the window-element instead. Is this a good approach? In that case, how can I tell what form is being submitted?
You should use the form's sumbit event, not the click on anything to process form submission.
$("#the-form").submit(register);
Also, with jQuery, you can just return false; at the end of the event handler. It does the same thing as e.preventDefault(); but in a cross-browser way.
And if you need to manually cause the form to be submitted (and hence your event handler to be executed), you can still do something like this:
$('.register a').click(function() {$("#the-form").submit();});
This way, this will always be the form in the "submit" event handler.
I'm writing some unit tests for an HTML 5 app that uses the HTML 5 form validation API. I've attached a submit event handler to the form that does some custom handling before serializing to JSON and passing it off to my server.
What I've discovered, though, is that if I initiate a jQuery submit() event on the form, even if it's invalid, my submit handler still gets called.
Instead, I'd expect my event handler not to have been called because the form is invalid.
I've created a JSFiddle to demonstrate (tested in Chrome 20):
http://jsfiddle.net/jonbca/SYg4h/22/
So, what gives?
Triggering the ".submit()" handler simply does not have anything to do with the HTML5 form validation mechanism. That mechanism is really quite independent of JavaScript, and in fact it's mostly unavailable from the DOM API. You can explicitly call "checkValidity()" on a form element, but that just returns a boolean result and does not do any of the visual form updates that happen when the user clicks a "submit" form control.
It's important to keep in mind that many of the fancy HTML5 "smart markup" behaviors are designed to allow things to happen without the need for JavaScript.
Try triggering the submit button:
$('#submitBtn').click();
If you don't have one, just do a hidden one, that replicates the action.
Fiddle: http://jsfiddle.net/SYg4h/30/
Try using a click handler on the button
$('#myform').submit(function (e) {
// check for validation here
var value = $('#foo').val();
if (!value || value == undefined)
$('#message').html('It did not submit');
else
$('#message').html("It submitted");
return false;
});
$('#submitBtn').click(function(){
$('#myform').submit();
});
Try this: http://jsfiddle.net/Cqzcu/4/
Check out this jsbin.
I have a form with a custom button that submits it via ajax (not a real submit button).
I'm using jquery-validation to validate the form, and running validate().checkForm() to validate it.
My question is - why don't the error messages on the specific fields appear when I do this? They appear all right when I'm using a standard submit button.
Edit: My example doesn't include the ajax submission, but just pretend it's there.
Because validate is listening for the submit event.
If you add $("form").submit(); inside the click event then it is fired.
http://jsbin.com/avuhed/edit#javascript,html,live
Piggy-backing on what #weezer said, you'll need to associate the form submission event with the button click, and you'll also want to put it inside the form itself. Right now it's sitting outside of it. For future updates, and sanity, it'll make your life easier to keep it grouped together.
The jquery validation is triggered by a standard form submit.
You may need to attach a .click handler to your custom submit button as so:
var isValid = $("#yourForm").valid();
if(isValid) {
// Do stuff
}
Yes, i have and if you put:
$("#submit").click(function() {
var isValid = $("#form").isValid();
if(isValid) {
alert('test');
}
});
Instead of what you have and move the custom button within the form, the validation works. http://jsbin.com/ajeyot/9