In the Web development will often encounter the need to dynamically monitor the value of the input box changes, if the use of onkeydown, onkeypress, onkeyup this several keyboard events to monitor, can not monitor the right key to copy, clip and paste these operations, processing combination shortcut key is also very troublesome. So this article introduces a perfect solution: HTML5 standard event Oninput and IE exclusive event Onpropertychange events to monitor input box value changes.
Oninput is a standard event for HTML5, which is useful for detecting textarea, Input:text, Input:password, and input:search elements that occur through the user interface and are triggered immediately after the content has been modified, unlike The onchange event needs to lose focus before triggering. The compatibility of the Oninput event in the mainstream browser is as follows:
From the table above, it can be seen that the Oninput event is not supported in the IE9 version, it is necessary to use IE-specific Onpropertychange event substitution, this event in the user interface changes or use the script directly modify the content of the two situations will trigger, there are several situations:
-modifies the state of the Input:checkbox or Input:radio element in the selection, checked property changes.
-The value of the Input:text or TEXTAREA element has been modified, and the Value property has changed.
-The selected item of the SELECT element has been modified and the SelectedIndex property has changed.
After you hear the Onpropertychange event, you can use the PropertyName property of the event to get the name of the property that changed.
Collection Oninput & Onpropertychange The sample code that listens for the contents of the input box is as follows:
Using the JQuery library, you only need to bind both Oninput and Onpropertychange two events, the sample code is as follows:
$ (' textarea '). Bind (' input PropertyChange ', function () {
$ ('. Msg '). HTML ($ (this). Val (). length + ' characters ');
} );
The last thing to note is that both Oninput and Onpropertychange have a small bug in IE9, which is not triggered when content is deleted by the cut and delete commands in the right-click menu menu, and other versions of IE are normal. There are no good solutions at the moment. However, Oninput & Onpropertychange is still the best way to monitor the changes in input box values, if you have a better approach, welcome to participate in the discussion.