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

Well that pretty much happens.

We have all seen this before: a button becomes active and clickable only after we put something in the input file. I am trying to implement this. I think either I went wrong and I had to put my jQuery selectors differently or just something was 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 a β€œclick” in the console several times, but if I add console.log('key pressed')before the tag if, it will be shown once for keydown, as expected.

Any tips?

+5
source share
4 answers

disabled. click:

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

click:

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

JSFiddle.

, , <a>

, , , , :

HTML:

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

JavaScript:

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

JavaScript:

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

    alert('Clicked!');
});

JSFiddle.

+5

click keyup.

, , , , .inactive :

$('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

+2

, (keyup), , .send-feedback.

.send-feedback,

(nbr textarea) * ( .send-feedback)

"clicked".

click, .send-feedback "".

:

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

I created this script for you, hope this helps:

This happens as follows:

var el = $(this);
var btn = $("#btnDoStuff");

if(el.val().length > 0)
    btn.prop("disabled", false);
else
    btn.prop("disabled", true);

I hope I do not understand the problem.

0
source

All Articles