jQuery blur event firing on load, instead of when expected - javascript

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
});
});

Related

How to run a Javascript/Jquery Function using both $(document).ready(function() and Another Event Function?

I'm not a javascript/jquery coder, and not sure if what I'm trying to do is possible.
I have a html/php/ajax form that is updated an sql database as the user fills it out. As they fill the form, there is a progress bar ran by javascript/jquery that updates as the user types in the input. The start of the function looks like this:
$("#update input").keyup(function() {
This works great. My problem is when the page is reloaded. My code is pulling sql data from the database to fill the value of every input on the page that has a value so that a user can come back and completely the form later. When the user reloads the page, the only way for the script to activate is if the user types in an input field.
I thought I would fix the issue by changing the my initial javascript/jquery function with $(document).ready(function() . This caused the script to only run when the page was loaded and not when the form was being filled out. I need both the script to run on page ready, and when a user is typing in the input filled. Is there a way I can run both $(document).ready(function() AND $("#update input").keyup(function() { simultaneously? Or is there a better why to accomplish this? Thanks!
Let me know if I need to post more code.
Here's a generic approach attaching declared functions to events.
function handler (e) {}
element.addEventListener('click', handler);
You're free to call handler everywhere, also inside $(document).ready, or if there's no other code in your DOMReady handler, you can just pass a reference as an argument:
$(document).ready(handler);
In your specific case you most likely want something like this:
$(document).ready(function () {
function handler (e) {...}
handler();
$("#update input").keyup(handler);
});
If the handler function uses the event object (e in the example), in modern browsers it's also available as a global event object, or in jQuery, e.originalEvent. The object doesn't exist if there's no event fired, though, in that case you've to pass a fake event object, containing the provided properties, to the handler, if it is needed.

event trigger on submit

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);

Why is this Javascript code executed twice?

When a link is clicked on my site the Javascript code below is executed, if the condition is true it will display an alert dialog. When the user selects the OK button in the alert dialog the block of code is executed again.
So the alert closes, the code below is executed for a second time and the alert dialog is displayed again. When the used selects the OK button on the alert dialog the second time the alert dialog is closed for good.
How can I prevent the code below being executed twice?
$("#my-button").click(function() {
var login = someVar;
if(!someVar || someVar == ''){
$('.close-reveal-modal').click();
alert(myMessage);
}
});
Check if you are adding the click handler twice, maybe that is what is causing that behavior.
In that case remove one of them.
From the very limited information that's provided, this is all that I can think of as going wrong:
$('.close-reveal-modal').click();
This piece of code should have some kind of function which is executed to display a similar Alert Box.
A complete code would be more useful for a complete answer!
Might not have anything to do with that code at all. Check to make sure that your javascript file isn't being called twice in the same app.
From what we have here, I'm guessing that your .close-reveal-modal element is in #my-button (or is the same html node).
When you trigger the click on it (by $('.close-reveal-modal').click();), it also trigger the click on its parent node, so on #my-button too.
I can be wrong, we need the HTML part (a fiddle would be great) to validate my theory.

In jquery How to tell what form is being submitted?

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.

Display native validation message in JavaScript

I'm currently developing a form which will be powered by HTML5 features and jQuery. One of the things I've been tasked with is ensuring that the native "Please fill in this field" message is still available to browsers which natively support validation.
My setup looks like so:
|----------|
| FORM |
|----------|
===BUTTON===
The form has several parts to it, and so the button is global across them all. The form then slides to the next section if complete.
Here is what I have now, this correctly fires the button event to the form and triggers a submit event.
$(".next").click(function() {
var $incoming = $(".nextPart #" + (currentSlide));
var incomingID = $incoming.data("cardid");
var partCode = "form-" + incomingID;
$("form[name='" + partCode + "']").trigger("submit");
});
$("form").bind('submit', function(event) {
var goForth = true;
if(!event.currentTarget.checkValidity()) goForth = false;
if(!goForth) return false;
/* Do some stuff with progress bar and more things */
return true;
});
However, even though the form submit fails, there is no validation message. Is there a way to pragmatically fire this on an element, or have I done something stupid?
For clarification, this is a screenshot of the validation message I am on about.
instead of event.currentTarget.checkValidity -- do this...
function checkValidity(elem) {
// check validity here
// retun true/false
}
and then in your submit handler do this...
if(checkValidity(event.currentTarget)) { ...
Also, it is generally NOT a good idea to trigger native browser events -- trigger is good for custom events -- if you need to submit the form you can call the submit() method of the form object like this..
$("form[name='" + partCode + "']").get(0).submit();
As I described in my first post, I was using a click event on a button which was in a global scope. This was then sending a submit action to the form which, although was sending the form to be submitted, it wasn't firing the bubble event (whatever the hell that is) on the elements.
To fix this, I wrapped all of my slides in one form instead of multiples. I kept my submit button outside of the slides, so it still acted as a global navigation item.
Removing the click event from this button and changing the type of it to submit now gets the bubble displaying.
Not the best fix, since the bubble should be able to be trigged without having to submit the form, however, I guess with HTML5 validation, you can define the parameters for what is accepted and what isn't.

Categories

Resources