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.
Related
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);
I want to submit a form using ajax. So I am not using the type=submit. I am using a onClick event on a link(<a>) to send the form data using ajax. I also want to take advantage of HTML5 form validation capabilities.
So before sending the data, I used the function .checkValidity to check the validity of the form.
If it returns true then I send the data. But when it return false I want to show user that the form is invalid using HTML5 default notifying scheme. But I don't know how to trigger that.
Is there is any way to show the validation of the form programmatically.
One way to do is trigger the submit event if checkValidity return false. But this will refresh the page. I don't want to change the state of the page.
checkValidity only checks validity and inform the program. It doesn't inform the user interactively.
We have exactly the same problem and we tried very different things and a lot of them were hacks like pseudo submits and event.preventDefault() approaches. All in all i must say that HTML5 validation is nice in general but really bad in practice because its not possible to display backend validation errors the same way as frontend validation errors.
And only god knows why the HTML5 folks didnt thought about a simple API where we can trigger the validation like this element.triggerValidationMessage('my message');
You can do it if you let your form have a submit button and return false!
And you cán do it in the same event handler as the non-submits!
So, first test if you are part of a form and if so, make it check Validity and never return true (even if valid)!
$('.ajx')
.on("submit click", function(e) {
var $this = $(this)
//Force native form validating and notification
form = $this.closest('form')[0]
if (form) {
//Follow through with form submit (element must be of submit type!)
if(!form.checkValidity()) {
//don't ask me!
sleep(3000);
return false
}
}
//only preventDEfault AFTER possible form element click
e.preventDefault()
//...your project further ajax code
//Makes sure your form never submits
if (e.type=='submit') return false
}
Small downside: You have to do this on the submit button, but it's always possible to change your <a> into type=submit. You don't have to change the non form <a>'s though!
I'm working on a project which will require some form validation, which I'm using jQuery for.
There's a field where a user will enter their email, and once they have filled out that field I want to check it.
Currently, the first part of my JavaScript looks like this:
$(window).load(function()
{
var email = $("#registerEmail");
email.blur(alert("stuff")); //will call a validation function
Right now, I get the "stuff" alert as soon as the page loads. My understanding was that blur would only fire once an element gained focus and then lost it -- am I misunderstanding this? Shouldn't this alert only execute once a user clicks or types in the email form and then clicks or types somewhere else, rather than immediately when the page loads?
You are actually executing the alert function when you do it that way. You need to provide a function that can be called later. Do
email.blur(function () {
alert("stuff");
});
$(document).ready(function(){
$("#registerEmail").blur(function(){
//your alert here
});
});
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