Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery: click event called $('textarea').val().trim().length times

Well, that's pretty much what happens.

We've all seen this before: button becomes active and clickable only after we've put something in an input filed. I'm trying to implement that. I guess either I've gone the wrong way and I should've placed my jQuery selectors differently, or it's just something wrong with the code.

$('textarea').bind({'keyup' : function(){
    if ($(this).val().trim().length){
        $('.send-feedback').removeClass('inactive').click(function(){
            console.log('clicked');
        });
    } else {
        $('.send-feedback').addClass('inactive').off('click');
    }
}})

Basically, I see 'clicked' in the console multiple times, but if I add console.log('key pressed') before the if check, it's being shown once per keydown, as expected.

Any advice?

like image 469
Anton Matyulkov Avatar asked Mar 28 '13 10:03

Anton Matyulkov


2 Answers

You may as well just set the button to disabled. This will prevent the click event from firing:

if($('textarea').val().trim().length > 0)
    $('.send-feedback').removeAttr('disabled');
else
    $('.send-feedback').attr('disabled','disabled');

Then separate your click function:

$('textarea').on('input', function(){ ... });
$('.send-feedback').on('click', function() { ... });

JSFiddle example.

thing is, it's not really a button, but an <a>

In that case you can use classes, which I suppose is sort of what you're currently doing:

HTML:

<a href="#" class="send-feedback disabled">Click</a>

JavaScript textarea length check:

if( $(this).val().trim().length > 0 )
    $('.send-feedback').removeClass('disabled');
else
    $('.send-feedback').addClass('disabled');

JavaScript click function:

$('.send-feedback').on('click', function(e) {
    e.preventDefault();
    if($(this).hasClass('disabled'))
        return;

    alert('Clicked!');
});

JSFiddle example.

like image 131
James Donnelly Avatar answered Nov 20 '22 21:11

James Donnelly


You are rebinding the click event on every keyup event.

Change the code to check that the button is inactive before binding the click by adding .inactive to the selector:

$('textarea').bind({'keyup' : function(){
    if ($(this).val().trim().length){
        $('.send-feedback.inactive').removeClass('inactive').click(function(){
            console.log('clicked');
        });
    } else {
        $('.send-feedback').addClass('inactive').off('click');
    }
}})

JSFiddle Example

like image 2
Richard Dalton Avatar answered Nov 20 '22 21:11

Richard Dalton