Eric J.
Eric J.

Reputation: 150148

React when Browser Text Input Changed through Mouse Action

I have a text input field and a checkbox. The checkbox must be disabled if and only if there is input in the text field. I have a solution that works great for most scenarios:

HTML:

<input type="text" id="search" />
<input type="checkbox" id="cb" />
<label for="cb">Enabled only if no search term</label>

jQuery:

$('#search').keyup(function (e) {
    var enable = $(this).val() == 0;
    if (enable) {
        $('#cb').removeAttr('disabled');
    } else {
        $('#cb').attr('disabled', 'disabled');
    }
});

See it live on jsFiddle.

This works when text is typed or removed using the keyboard, and when text is pasted using the keyboard.

It fails if the user pastes text using the right-click context menu, or if the user presses the little "X" that IE adds to the input field to allow the input field to be cleared.

Question

How can I improve the code so that it also works in those scenarios? Waiting for the textbox to lose focus would provide an inferior user experience.

Upvotes: 1

Views: 481

Answers (2)

Eric J.
Eric J.

Reputation: 150148

The Real Time Validation jQuery Plugin solves this issue. However, it does not seem to work currently with delegated events.

Implementing this requires binding events to the keyup event, and a couple other events if you want to detect text changes on cut and paste. Even if you're a JavaScript god it's tedious to keeping writing this logic over and over again. Be smart and use the ZURB text change event plugin instead.

Upvotes: 1

Lowkase
Lowkase

Reputation: 5699

You can use the jquery change method:

http://jsfiddle.net/WDMCX/1/

$('#search').change(function() {

    if( $(this).val() === '' ){
        $('#cb').attr('disabled', 'disabled');
    } else {
        $('#cb').removeAttr('disabled');
    }

});

Upvotes: 0

Related Questions