Tutorial :Is there a better onchange?



Question:

I've got a textarea, and when it changes, I'd like a function to be called.

However, the standard onchange event fires after the focus leaves the textarea. What I really want is for the even to fire as soon as the user begins typing.

I could bind onkeypress, but that doesn't handle, say, pasting text into the textarea with the mouse. Plus it fires for Tab and other non-changing keypresses.

Is there a better solution?


Solution:1

You could add a

onkeyup="SomeFunction();"  

Edit: Aah, too quick. I did not see the "on mouse paste".

Edit 2:

<script type="text/javascript">      var ival = "";      var checkup = window.setInterval("checkChange();", 100);      function checkChange() {          var nval = document.getElementById("test").value;          if (nval!=ival) { alert("change in the text"); ival=nval; }       }  </script>  <input type="text" id="test" name="test" value="" />  

Example from: http://bytes.com/topic/javascript/answers/703623-capturing-event-when-user-right-click-paste-into-text-box


Solution:2

onKeyPress will work, just in the case of pasted coded - you'll know it pasted because it will contain a newline character where as if you were just typing into a textfield - the newline character wouldn't be present

Just check for a newline and use onKeyPress


Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Previous
Next Post »