views:

49

answers:

3

I have a textbox and want an event triggered whenever it is updated, whether through key presses, pasted from clipboard, or whatever else is possible.

Is binding to the keyup event sufficient or is there a better way?

A: 

I think it depends on how often you want to listen I think ketup will do it but onchange may be less intenseive and get you the same effect it just depends on what your doing

mcgrailm
+1  A: 

I did the same thing in a text field with this code:

$(document).ready(function(){

    $('#link').keyup(function(event){       

        if($(this).val().length > 30 && this.value != this.lastValue){
            if (this.timer) clearTimeout(this.timer);

            if(!$('#ajax-aguarde').length)
            {
                $('<p id="ajax-aguarde"></p>').appendTo($('#link-element'));
            }
            $('#ajax-aguarde').html('Wait, loading...');

            if($('#posts').length){
                $('#posts').remove();
                $('#p-ultimos').remove();
            }

            str = this.value;
            url = $('#ajaxurl').val();

            this.timer = setTimeout(function () {
                $.post(
                url,
                { link: str, format: 'json' }, 
                function(data){

                    if(data.error == 1){
                        $('#ajax-aguarde').html('Error...');
                    } else {
                        $('#ajax-aguarde').remove();
                    }

                    if(data.titulo.length){
                        $('#titulo').val(data.titulo);
                    }
                    if(data.descricao.length){
                        $('#descricao').val(data.descricao);
                    }

                    $('<p id="p-ultimos">Last posts:</p>').appendTo($('#link-element'));
                    $('<ul id="posts"></ul>').appendTo($('#link-element'));

                    $.each(data.posts, function(index, post) { 
                        $('<li id="post' + index + '"></li>').appendTo($('#posts'));
                        $('#post' + index).html(post.title);
                    });


                },
                "json"
                );
            },1000);

            this.lastValue = this.value;
        }

    });

    setTimeout(function() { $('#link').keyup(); },500);
});

I have setTimeout to ensure some events that did not get triggered

Keyne
+2  A: 

you can bind multiple events like this:

$('#textbox').bind('keyup change blur', function() {
    // stuff to do when any of these events fire
});

it sounds like change() alone should work for you, though.

Here is the API doc

carillonator
change was my first thought too but I found it doesn't fire when the text changes. The key events do.
Plumo