Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to detect textbox change event from javascript

I have a textbox asp.net server control. I am modifying the value of textbox from javascript i want to detect when the textbox text is changed. I tried onchange event which gets called on lost foucs when the text changes. But in my case i an changing text from Javascript. how can i achieve this?

like image 671
Ulhas Tuscano Avatar asked Apr 26 '11 06:04

Ulhas Tuscano


People also ask

How do you detect change in text input box?

Answer: Use the input Event You can bind the input event to an input text box using on() method to detect any change in it.

How to detect change in input JavaScript?

Approach 2: There are few other events that can be used to detect the change in content of textbox. Use any or all of them onchange event, onpropertychange event, onkeyup event, onpaste event and oninput event in the input element and call a function to see the effect. click outside of it to see.

How to get text change event in jQuery?

The change() method triggers the change event, or attaches a function to run when a change event occurs. Note: For select menus, the change event occurs when an option is selected. For text fields or text areas, the change event occurs when the field loses focus, after the content has been changed.

How to detect change in input jQuery?

The change() is an inbuilt method in jQuery that is used to detect the change in value of input fields. This method works only on the “<input>, <textarea> and <select>” elements. Parameter: It accepts an optional parameter “function”. Return Value: It returns the element with the modification.


1 Answers

Updating the value property won't trigger the change event. The change event is triggered by the user.

You can either write a function which changes the value and does whatever else you need to do...

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

...or poll the textarea's value...

(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);
})();

...or explicitly call the onchange() event yourself.

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

(Assuming you set the event up with onchange property.)

The workarounds are not terribly great solutions. Either way, you need to do some intervention to trigger extra code when updating a textarea's value property.

like image 91
alex Avatar answered Oct 16 '22 17:10

alex