Dan Eastwell schrieb:
> Hi all,
> 
> I've just started using jquery, and as you can tell from my blog, very 
> close to just having started javascript, but I'm determined to do things 
> properly.
> 
> I've written a post function that, for the sake of argument, pops an 
> alert when you submit a form.
> 
> $(document).ready(function(){
>     initialiseForm();
> });
> 
> function initialiseForm() {
> $("form#fPollX").bind("submit", post());
> }
> 
> function post() {
>  alert('hello');
>  return false;
> }
> 
> This works fine. Now I want to abstract it out so that any form can (for 
> this version anyway) return its own message, based (currently) on a 
> switch in post(). Either or neither form or both may be on the page.
> 
> So now I've tried:
> 
> $(document).ready(function(){
>     initialiseForm("fPollX");
>     initialiseForm("fPollY");
> });
> 
> function initialiseForm(formID) {
>     if (!document.getElementById) return false;
>     if(document.getElementById(formID)){
>         theForm = "form#" + formID;
>         $(theForm).bind("submit", post(formID));
>     }
> }
> 
> function post(formName) {
>     switch(formName){
>     case "fPollX":
>         alert('hello X ' + formName);
>         return false;
>     break;
>     case "fPollY":
>         alert('hello Y ' + formName);
>         return false;
>     break;
>     default:
>         return false;
>     }   
> }
> 
> The problem with this, I think is the fact I'm trying to 'bind' a 
> function to a variable using the $( ) function. In this case, the post() 
> function isn't called, it just runs ( e.g. alerting "hello X fPollX") 
> the correct case, if the form is on the page).
> 
> The question here is either: how do I bind a function to a submit event, 
> if I don't know exactly what the form's going to be called in the function?

Create a function that returns a function - that saves you the hardcoded 
variables in the switch statement and makes the code a lot shorter and 
flexible:

function getPost(formId) {
     return function() {
         alert('hello X ' + formId);
         return false;
     };
}

function initialiseForm(formId) {
     $(formId).bind('submit', getPost(formId));
}

initialiseForm('#fPollX');

I don't think that you need to check for document.getElementById, if you 
are using jQuery anyway you can pretty much assume that. jQuery itself 
should fail gracefully in these legacy browsers that don't support that...

You also shouldn't use a type selector together with an id 
("form#yourId"), that slows the whole query down (use "#yourId").

Also note that you have to pass in a function *reference* to the bind 
function, not the call itself. In your first example you used "post()" 
(which calls the function immediatly) instead of "post".


-- Klaus

_______________________________________________
jQuery mailing list
discuss@jquery.com
http://jquery.com/discuss/

Reply via email to