开发者

Jquery text change event

开发者 https://www.devze.com 2023-03-22 07:47 出处:网络
I need to fire an event anytime the content of a textbox has changed. I cant use keyup nor can I use keypress.

I need to fire an event anytime the content of a textbox has changed.

I cant use keyup nor can I use keypress.

Keyup and keydown doesn't work if you hold down on the key.

Keypress triggers before the text has actually changed. It doesn't recognize backspace or delete either.

So now I'm 开发者_StackOverflow中文版assuming I'm going to have to build some custom logic or download a plugin. Are there any plugins out there? Or if I should build one, what constraints should I look out for?

For eg. Facebook does it with their search at the top. you can press and hold.

another example is writing a stackoverflow question. Right below the editor, the contents are copied in real time, backspace and everythng works. How do they do it?


I just took a look at SO's source. It looks like they do something a lot like this:

function updatePreview(){
    $('div').text($('textarea').val());
}

$('textarea').bind('keypress', function(){
        setTimeout(updatePreview, 1);
    }
);​

They do some extra stuff to make HTML tags for bold and italics and links and such and they time it. They increase the delay from 1 to longer if it takes too long to generate the HTML.


I had success using jQuery (in Chrome). If you hold a key down, it counts every change, not just the first one, and it counts non-print keys like backspace.

HTML

<input id="txt" type="text" />
<span id="changeCount">0</span>

JavaScript

$('#txt').keydown(function(event) {
    // Don't count the keys which don't actually change
    // the text. The four below are the arrow keys, but
    // there are more that I omitted for brevity.
    if (event.which != 37 && event.which != 38 &&
        event.which != 39 && event.which != 40) {

        // Replace the two lines below with whatever you want to
        // do when the text changes.
        var count = parseInt($('#changeCount').text(), 10) + 1;
        $('#changeCount').text(count);

    }
});

Like I said above, you'll want to filter out all of the key codes that don't change the text, like ctrl, shift, alt, enter, etc. There's also the boundary condition if you press the backspace or delete key when the textbox is empty or if the textbox has a maximum length and a printable key is pressed, but it's not terribly difficult to handle those either.

Here's a working jsfiddle example.


How about a poll? Do a setInterval and call a function that checks the text say every 500ms? You don't want to detect content change on every key anyway because it gets kinda slow in some older browser/older computer and you would notice a lag between typing and the text displaying.


You need a watcher type functionality.

It resorts to setInterval polling if the other features are not available: http://james.padolsey.com/javascript/monitoring-dom-properties/


I have a simple solution that we use happily in one of our project.

you can try it @ http://jsfiddle.net/zSFdp/17/

var i = 0;
$('#text').bind('check_changed', function(){
    var t = $(this);

    // do something after certain interval, for better performance
    delayRun('my_text', function(){
        var pv = t.data('prev_val');

        // if previous value is undefined or not equals to the current value then blablabla
        if(pv == undefined || pv != t.val()){
            $('#count').html(++i);
            t.data('prev_val', t.val());
        }
    }, 1000);
})
// if the textbox is changed via typing
.keydown(function(){$(this).trigger('check_changed')})
// if the textbox is changed via 'paste' action from mouse context menu
.bind('paste', function(){$(this).trigger('check_changed')});

// clicking the flush button can force all pending functions to be run immediately
// e.g., if you want to submit the form, all delayed functions or validations should be called before submitting. 
// delayRun.flush() is the method for this purpose
$('#flush').click(function(){ delayRun.flush(); });

The delayRun() function

;(function(g){
    var delayRuns = {};
    var allFuncs = {};

    g.delayRun = function(id, func, delay){
        if(delay == undefined) delay = 200;
        if(delayRuns[id] != null){
            clearTimeout(delayRuns[id]);
            delete delayRuns[id];
            delete allFuncs[id];
        }
        allFuncs[id] = func;
        delayRuns[id] = setTimeout(function(){
            func();
            delete allFuncs[id];
            delete delayRuns[id];
        }, delay);
    };

    g.delayRun.flush = function(){
        for(var i in delayRuns){
            if(delayRuns.hasOwnProperty(i)){
                clearTimeout(delayRuns[i]);
                allFuncs[i]();
                delete delayRuns[i];
                delete allFuncs[i];
            }
        }
    };
})(window);


Zurb has a great plugin which might be useful for you http://www.zurb.com/playground/jquery-text-change-custom-event

0

精彩评论

暂无评论...
验证码 换一张
取 消