How to detect a textbox's content has changed

后端 未结 15 2058
猫巷女王i
猫巷女王i 2020-11-22 16:10

I want to detect whenever a textbox\'s content has changed. I can use the keyup method, but that will also detect keystrokes which do not generate letters, like the arrow ke

15条回答
  •  眼角桃花
    2020-11-22 16:10

    Something like this should work, mainly because focus and focusout would end up with two separate values. I'm using data here because it stores values in the element but doesn't touch the DOM. It is also an easy way to store the value connected to its element. You could just as easily use a higher-scoped variable.

    var changed = false;
    
    $('textbox').on('focus', function(e) {
        $(this).data('current-val', $(this).text();
    });
    
    $('textbox').on('focusout', function(e) {
        if ($(this).data('current-val') != $(this).text())
            changed = true;
        }
        console.log('Changed Result', changed);
    }
    

提交回复
热议问题