Reputation: 1681
I defined this function which checks if a input field is empty or not
function hasValue() {
if ( !!$.trim( $(this).val() ) )
return true;
}
It just works fine for filtering a jQuery Collection
$('#form').find( '.email' ).filter( hasValue );
But I also want to reuse the hasValue()
-function for toggeling a class.
$('.input').change( function () {
var empty = hasValue().apply( $(this) ); //throws an error
// var empty = $(this).hasValue(); //doesn't work either
$('#box').find('.required-tmp').toggleClass('required', empty );
});
Any help is appreciated.
Upvotes: 1
Views: 2106
Reputation: 2062
Juste pass this to apply. And don't execute () before :
hasValue.apply(this);
If you want to have a better use of your function it must accept an element as parameter it's not a good pattern to use this
like this. Prefer to pass the element in arguments
function hasValue(elem) {
return !!$.trim($(elem).val());
}
And then the usage is the same for map :
$('#form').find( '.email' ).filter( hasValue );
And :
$('.input').change( function () {
var empty = hasValue(elem); //throws an error
$('#box').find('.required-tmp').toggleClass('required', empty );
});
Upvotes: 1
Reputation: 44
fn.apply syntax should be like hasValue.apply( $(this) ) instead of hasValue().apply( $(this) )
May be that will solve your problem.
Thanks & Regards, Charly
Upvotes: 0
Reputation: 117
Why are you using double negation in the hasValue method?
Secondly, use apply as:
var empty = hasValue.apply( this );
This will pass the element as the parameter which you can use there!
Thirdly, for checking whether the value exists, you can just use type check instead of trim as:
if(typeof $(this).val !== 'undefined'){
return true;
}
See if that works for you!
Upvotes: 1
Reputation: 1360
$('.input').change( function () {
var empty = hasValue.apply( $(this) ); //apply function should be used this way .
// var empty = $(this).hasValue(); //doesn't work either
$('#box').find('.required-tmp').toggleClass('required', empty );
});
Upvotes: 1