How to detect a textbox's content has changed

后端 未结 15 1894
猫巷女王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:30

    How about this:

    < jQuery 1.7

    $("#input").bind("propertychange change keyup paste input", function(){
        // do stuff;
    });
    

    > jQuery 1.7

    $("#input").on("propertychange change keyup paste input", function(){
        // do stuff;
    });
    

    This works in IE8/IE9, FF, Chrome

    0 讨论(0)
  • 2020-11-22 16:30

    Use the textchange event via customized jQuery shim for cross-browser input compatibility. http://benalpert.com/2013/06/18/a-near-perfect-oninput-shim-for-ie-8-and-9.html (most recently forked github: https://github.com/pandell/jquery-splendid-textchange/blob/master/jquery.splendid.textchange.js)

    This handles all input tags including <textarea>content</textarea>, which does not always work with change keyup etc. (!) Only jQuery on("input propertychange") handles <textarea> tags consistently, and the above is a shim for all browsers that don't understand input event.

    <!DOCTYPE html>
    <html>
    <head>
    <script class="jsbin" src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
    <script src="https://raw.githubusercontent.com/pandell/jquery-splendid-textchange/master/jquery.splendid.textchange.js"></script>
    <meta charset=utf-8 />
    <title>splendid textchange test</title>
    
    <script> // this is all you have to do. using splendid.textchange.js
    
    $('textarea').on("textchange",function(){ 
      yourFunctionHere($(this).val());    });  
    
    </script>
    </head>
    <body>
      <textarea style="height:3em;width:90%"></textarea>
    </body>
    </html>
    

    JS Bin test

    This also handles paste, delete, and doesn't duplicate effort on keyup.

    If not using a shim, use jQuery on("input propertychange") events.

    // works with most recent browsers (use this if not using src="...splendid.textchange.js")
    
    $('textarea').on("input propertychange",function(){ 
      yourFunctionHere($(this).val());    
    });  
    
    0 讨论(0)
  • 2020-11-22 16:31

    do you consider using change event ?

    $("#myTextBox").change(function() { alert("content changed"); });
    
    0 讨论(0)
提交回复
热议问题