How to detect textbox change event from javascript

I have an asp.net server control text box. I am changing the value of a text field from javascript that I want to detect when changing the text of the text field. I tried the onchange event, which is raised when foucs is lost when the text changes. But in my case, I am changing the text from Javascript. how can i achieve this

+5
source share
4 answers

Updating a property valuewill not result in a change event. The change event is triggered by the user.

You can either write a function that changes the value, and does everything you need ...

function changeTextarea(str) {
   document.getElementById('a').value = str;
   // Whatever else you need to do.
}

... or query the meaning textarea...

(function() {
   var text = getText();   
   var getText = function() {
      return document.getElementById('a').value;
   }  

   setInterval(function() {
      var newtext = getText();
      if (text !== newText) {
          // The value has changed.
      }
      text = newText; 
   }, 100);
})();

... onchange() .

document.getElementById('a').onchange();

(, onchange.)

- . - , textarea value.

+6

javascript , , . Page.GetPostBackEventReference() , , .

, javascript javascript, .NET hasle , , Ajax.NET

, , onchange.

0

Using jquery, you can assign a change handler and call the handler as follows:

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
    <script src="Scripts/jquery-1.4.1.js" type="text/javascript"></script>
    <script type="text/javascript">
        $(document).ready(function () {
            //makes 'DetectChange' the handler when TextBox1 changes...
            $('#TextBox1').change(function () {
                DetectChange();
            });
         });

        function DetectChange() {
            alert("TextBox1 has been changed");
        }

        function ClickTheButton() {
            // .val actually 'changes the value'
            // while you have to add .change() to invoke the actual change event handler...
            $('#TextBox1').val("Changed When Button Clicked").change();

            //return false prevents the click event of the button from doing a post back
            //keeping everything on the client for this sample..
            return false;
        }
    </script>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
        <input id="Button1" type="button" value="Change TextBox1" onclick="return ClickTheButton();"  />
    </div>
    </form>
</body>
</html>
0
source

If you can use jQuery, it will be something like this

$('#id_of_text_area').change(function(){
    //do something
});
-1
source

All Articles