Real -Time listening text box value changes are very common features, usually the simplest way is to use Keyup,keydown to implement, but this method has two problems, one is when the direct copy and paste can not hear the event, another problem is on the mobile side, Use Delete key to delete input time also can't hear!
Workaround:
1. Using the onchange Event
The onchange event is triggered when the contents of the text box change and lose focus.
2, the more perfect solution: Oninput and Onproper
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 is modified, unlike The onchange event needs to lose focus before it is triggered. The compatibility of Oninput events in mainstream browsers is as follows:
As can be seen from the table above, theoninput event is not supported in the following versions of IE9 and requires the use of IE-specific Onpropertychange event substitution, which is triggered when the user interface changes or the content is modified directly using a script. There are several situations:
- Modified the Input:checkbox or Input:radio element selection state, the checked attribute changed.
- The value of the Input:text or TEXTAREA element has been modified, and the property of value 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 has changed.
The sample code for collection Oninput & onpropertychange monitoring input box content changes is as follows:
Firefox, Google Chrome, Opera, Safari, Internet Explorer from version 9
function Oninput (event) {
alert ("The new content:" + event.target.value);}
Internet Explorer
function Onpropchanged (event) {
if (event.propertyName.toLowerCase () = = "Value") { alert ("The new content:" + Event.srcElement.value); c4/> }}
The page structure is as follows:
<type= "text" oninput= "Oninput (event)" Onpropertychange= "onpropchanged (event)" value= "Text field"/>
Then call the function:
$ (' textarea '). Bind (' input PropertyChange ', function () { $ ('. Msg '). HTML ($ (this). Val (). length + ' characters ');});
JavaScript---Real-time monitoring of changes in input box values