简体   繁体   中英

Merge two functions in jScript

I need to call a PHP script using AJAX on my page (form validation). I'm quite handy with PHP but not very good with javascrip, jScript or any other client side language so I've found a free demo script that fills my needs and now I'm playing around with it just to see if I can learn something in the process. One thing I'm curious about if I can merge two functions into one.

The functions looks basically like this:

// When user changes something in the form
$("#signup").change(function()
{
    // ... validation code here
}

// When the form (page) first loads
$("#signup").ready(function()
{
    // ... validation code here
}

The first function validates the form if something is changed.

Sometimes users will submit the form prematurely (by pressing enter, for example) and in that case the validation will not occur again until user input changes something in the form.

I use the validation result to decide what class to apply to the input elements (to tell the user what is done and not) and I want this to stay (or happened again immediately ) if the form is submitted without being complete. I know I can apply form validation that wont let user submit until all required fields are filled out but let's pretend this is not possible for some unknown reason...

The second function is just a copy of the first one and validates the form as soon as the page loads. This one was not originally in the demo script but I figured out that I could duplicate the first function and change the word "change" to "ready" to get my form validated as I wanted.

Now, just out of curiosity, is there a way to merge those into one function instead of having two identical? Something like the OR operator in PHP:

$("#signup").change(function() || $("#signup").ready(function()
{
    // ... validation code here
}

Edit: yes, I have googled about it. Unsuccessfully though, maybe due to my lacking javascript/jScript knowledge I'm not using the correct search terms...

There's no such thing as what you're describing, but this gives you the same effect.

var validate = function () {
    // ... validation code here
}

$("#signup").change(validate);
$("#signup").ready(validate);

You can create a function, assign to to a variable and then have a reference to that function. That reference can then be passed to anything that requires a function as a parameter - .change, .ready, setTimeout, setInterval, etc., etc.

There are ways to go about this, but since we 're talking jQuery for me the most succinct is to immediately and on purpose trigger the change event handler:

$("#signup").change(function()
{
    // ... validation code here
}).trigger('change'); // causes validation to run

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM