Here's a function for use as an event handler that makes use of this
:
function validate() {
if (this.val() == '') {
return false;
}
}
$(':input').change(validate);
Here's the same function rewritten to take an argument, so that I can call it explicitly:
function validate(field) {
if ($(field).val() == '') {
return false;
}
}
validate($('#customer_name'));
How can I rewrite my validate
function to make it suitable for use as both an event handler, and as a standalone function for me to call?
There are various ways to do this. One is to use the second one taking the field as a parameter and set 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 an overridden this
:
function validate() {
if ($(this).val() == '') {
return false;
}
}
// Unchanged.
$(':input').change(validate);
// Use `$(...)` as "this" when calling validate.
validate.apply($('#customer_name'));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With