The perfect solution for js/jquery to monitor the value change of the input box in real time: oninput & onpropertychange

(1) Let’s talk about jquery first. If you use  the jQuery  library, you only need to bind the two events of on input and onpropertychange at the same time. Sample code:

$('#username').bind('input propertychange'function() {
    $('#content').html($(this).val().length + ' characters');
});

(2) For JS native writing, oninput is  a standard event of HTML5  . It is very useful for detecting the content changes of textarea, input:text, input:password and input:search through the user interface. After the content is modified Fired immediately, unlike the onchange event that needs to lose focus to fire. The compatibility of the oninput  event in mainstream browsers is as follows:

   

  As can be seen from the above table, the oninput  event is not supported in versions below IE9, and needs to be replaced by the IE-specific onpropertychange event. This event will be triggered when the user interface is changed or the content is directly modified by script. There are the following situations:

  • The selected state of the input:checkbox or input:radio element has been modified, and the checked attribute has changed.
  • The value of the input:text or textarea element is modified, and the value attribute changes.
  • The selected item of the select element is modified, and the selectedIndex property changes.

  After listening to the  onpropertychange  event, you can use the propertyName property of the event to get the changed property name.

  The sample code for collecting oninput & onpropertychange to monitor the content change of the input box is as follows:

 

 <head>
    <script type="text/javascript">
    // 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);
            }
        }
    </script>
</head>
<body>
    Please modify the contents of the text field.
    <input type="text" oninput="OnInput (event)" onpropertychange="OnPropChanged (event)"
     value="Text field" />
</body>

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=326986064&siteId=291194637