pbaldauf
pbaldauf

Reputation: 1681

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.

Upvotes: 1

Views: 2106

Answers (4)

Arnaud Gueras
Arnaud Gueras

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

Charly Arnold Geddam
Charly Arnold Geddam

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

Sukhminder Parmar
Sukhminder Parmar

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

passion
passion

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

Related Questions