There are various ways to do this. One of them is to use the second, taking the field as a parameter and setting the event handler using a closure:
function validate(field) { if ($(field).val() == '') { return false; } } // Use anonymous function to pass "this" to validate. $(':input').change(function() { validate(this); }); // Unchanged. validate($('#customer_name'));
Another way is to use the first form and use apply () to call it with this overridden:
function validate() { if ($(this).val() == '') { return false; } } // Unchanged. $(':input').change(validate); // Use `$(...)` as "this" when calling validate. validate.apply($('#customer_name'));
source share