Catch only keypresses that change input?

前端 未结 4 708
栀梦
栀梦 2020-11-28 09:39

I want to do something when a keypress changes the input of a textbox. I figure the keypress event would be best for this, but how do I know if it caused a chan

4条回答
  •  忘掉有多难
    2020-11-28 10:09

    I came up with this for autosaving a textarea. It uses a combination of the .keyUp() jQuery method to see if the content has changed. And then I update every 5 seconds because I don't want the form getting submitted every time it's changed!!!!

    var savePost = false;
    
    jQuery(document).ready(function() { 
        setInterval('autoSave()', 5000)
        $('input, textarea').keyup(function(){
            if (!savePost) {
                savePost = true;    
            }
        })
    })
    
    
    function autoSave() {
        if (savePost) {
            savePost = false;
            $('#post_submit, #task_submit').click();            
        }
    }
    

    I know it will fire even if the content hasn't changed but it was easier that hardcoding which keys I didn't want it to work for.

提交回复
热议问题