tony
tony

Reputation: 1536

jQuery and textarea change events

i just met a strange behavior jQuery and can't figure out any more or less slight solution. Say, i have textarea and button. I want to disable button if textarea is empty. For this i have a handler which does this job.

Here is the code:

// textarea control
var $textarea = $('#myTextarea');
var $button = $('#myButton');
$textarea.on('input propertychange', function() {
    if($textarea.val().length > 0) {
        $button.removeClass('disabled').removeAttr('disabled');
    } else {
        $button.addClass('disabled').attr('disabled', 'disabled');
    }
});
$button.on('click', function() {
    if ($button.attr("disabled") != null) {
        console.log('Disabled!');
        return false;
    } else {
        // do some stuff and eventually erase textarea 
        $textarea.val('');
    }
});

My trouble is when i erase textarea (the end of the code) it doesn't disable the button. Any ideas would be appreciated (actually it's slight adaptation of my code but the situation reflected pretty good, hope it would be clear for you, thanks!)

UPD Nothing found on stackoverflow doesn't help.

UPD2 As i said in the begin, i was looking not for workaround like force trigger event, i thought it's possible to catch any event fired by $textarea.val(); Sure @Madbreaks and @epascarello 's solutions work pretty good, thanks guys.

Upvotes: 1

Views: 4649

Answers (4)

Satya Kalluri
Satya Kalluri

Reputation: 5214

Recommend using this jQueryTextChange lib. Its a cross browser consistent one. The usages are clearly elaborated on the home page. http://zurb.com/playground/jquery-text-change-custom-event

Upvotes: 0

0x_Anakin
0x_Anakin

Reputation: 3269

Make sure you trim the value of your textarea and you dont have an white spaces when you get the length of the .val(). Also in case you use a text editor like ckEditor make sure you read their documentation on how to retrieve the text being written.

Upvotes: 0

Madbreaks
Madbreaks

Reputation: 19539

Maybe just add this:

else {
    // do some stuff and eventually erase textarea 
    $textarea.val('');
    // notify
    $textarea.trigger('propertychange');
}

Upvotes: 3

epascarello
epascarello

Reputation: 207511

problem is setting values with JavaScript does not normally trigger the events, but you can do it yourself.

$textarea.val('').trigger("input");

Upvotes: 3

Related Questions