pbaldauf pbaldauf - 2 months ago 17
Javascript Question

jQuery checking if input has value by function call

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.

Answer

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 );
});