1

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.

0

4 Answers 4

1

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 );
}); 
Sign up to request clarification or add additional context in comments.

Comments

1
$('.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 );
}); 

Comments

1

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!

Comments

0

fn.apply syntax should be like hasValue.apply( $(this) ) instead of hasValue().apply( $(this) )

May be that will solve your problem.

Thanks & Regards, Charly

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.