About JavaScript real-time display of textarea remaining characters

Source: Internet
Author: User
Tags event listener

Today in Baidu's project encountered a problem, is to achieve javascript real-time display textarea The function of the number of remaining characters, I see, this function is too simple, it is generally only with KeyDown and KeyUp event listener textarea character number on it, but QA detection needs to support the right mouse button Related events (including paste, undo, delete and cut, etc.), and requires the mouse to drag the text to textarea in real time to change the number of words, because these methods do not directly press the keyboard, so the light KeyDown and KeyUp event monitoring is not enough. The
now needs to use onpropertychange event, which is essentially different from onchange event, onpropertychange event is a change in the contents of the control immediately triggers the event (note: The Onpropertychange event is limited to the use of the normal html, using the html:textarea tag of struts does not contain this event, otherwise will error), but Onpropertychange is exclusive to the IE, And it seems that you can not use attachevent binding, but to direct obj.onpropertychange = fun; Other browsers need to replace oninput events.
A simple demo:

<! DOCTYPE html>oninput=function () {num=1000-this.value.length;    Remainobj.innerhtml= "remaining" +num+ "word"; }}</script></body>

Above this demo support Ff,chrome, IE7 and safari all events, including keyboard input, delete and direct mouse drag in, can also right mouse button inside the paste, delete, Undo and cut, opera also support these events, but do not support the mouse to drag directly into, IE8, IE9 does not support right-click events for the mouse (except for pasting). IE9 supports keyboard input and does not support keyboard deletion.
Onpropertychange events can not be directly inside the right mouse button delete and undo events, and there is no way to directly listen to these events, not like the right mouse button cut paste and direct drag, etc. to be able to use Onpaste, oncut and OnDrop monitoring, So there is no effective way to find out, if there are children shoes know, please inform, extremely grateful!
Demo

/* Calculate remaining characters, Base.remainword ("#textarea", "#wordsNum");*/    remainword:function (Textareaid, Totalnum, Remainid) {       /*        textareaid: id;        totalnum for textarea: Represents the total number of characters that can be entered;         Remainid: Displays the number of characters remaining id;        */        $ ( Textareaid). each (function () {            var-self = $ (this), Remainobj = $ (remainid), num = 0;            function fun () {& nbsp;               num = Totalnum-self.val () .length;                if (num > = 0) {                    Remainobj. CSS ("Color", "#828181"). HTML ("remaining" + num + "characters");                     self.removeclass ("error");                } else {                     remainobj.css ("Color", "#f00");                     Self.addclass ("Error"). Val (Self.val (). substring (0, totalnum));                }                 if (self.val () = = "") {                     Self.prev ("label"). HTML ("Please enter the question you want to say,We will give you feedback in time. ");               } else {                     Self.prev ("label"). HTML ("");                }           }            //ie with Onpropertychange event, IE9 does not support the right mouse button inside the deletion, Onpropertychange does not support a lot of events, need to write separately             if (/msie/i.test (navigator.useragent)) {                 Self[0].onpropertychange = fun;                Self.keydown (fun );                Self.keyup (fun); & NBsp;               base.bindevent (self[0], "paste", function () {                     SetTimeout (fun,);               });                 base.bindevent (self[0], "cut", function ( ) {                    SetTimeout (fun,);               });            } else {                 base.bindevent (self[0], "input", fun);            }           //opera and IE drag events             if (/opera/i.test (navigator.useragent) | | /msie/i.test (navigator.useragent)) {                //Prevent users from dragging content into the input box                  base.bindevent (self[0], "Drop", function () {                     setTimeout (fun,;     )           });                 base.bindevent (self[0], "Dragend", function () {                     SetTimeout (fun ,              &nbs);p; });           }        });   },

The final Solution for

is as follows:

/* Detection Word General fun*/checkword:function (obj, fun, speed) {//Part IE Onpropertychange event does not detect the right mouse button deletion and revocation events, opera's Oninput Can not detect the direct drag content to the TextArea event drop&&dragend, so this uses the timer to solve if (base.browser () = = "IE6" | | base.browser () = = "IE7" | | bas E.browser () = = "IE8" | | Base.browser () = = "IE9" | |            Base.browser () = = "Opera") {var timer;            $ (obj). focus (function () {timer = SetInterval (fun, speed);            });            $ (obj). blur (function () {clearinterval (timer);        }); //ff,chrome,safari and other browsers can use the Oninput event to listen to all events, including Keydown,keyup, the right mouse button cut,paste and delete, Undo and so on all events, including direct drag drop, etc. also support else        {base.bindevent (obj, "input", fun); }},/* Calculates the remaining characters, Base.remainword ("#textarea", "#wordsNum"); */Remainword:function (Textareaid, Remainid) {/*t            Extareaid: Represents the Id;remainid of textarea: id;*/$ (Textareaid) showing the number of characters remaining. each (function () {var-self = $ (this),        Remainobj = $ (Remainid),    num = 0;                function fun () {num = Base.totalnum-self.val (). length;                    if (num > 0) {remainobj.css ("color", "#828181"). HTML ("remaining" + num + "one");                    Self.removeclass ("error");                    if (num = = base.totalnum) {remainobj.html ("up" + Base.totalnum + "word");                    }} else {remainobj.css ("color", "#f00"). HTML ("0 remaining");                    Self.addclass ("error"); Prevent IE from entering all content after you can't ctrl + a SELECT All if (num! = 0) {self.val (Self.val (). substring (0, base.t                        Otalnum));                        Prevents the entry of the characters in front of the input, and the subsequent character self.unbind ("KeyDown") is removed; Self.keydown (Event) {//Excludes some delete buttons and direction buttons, etc., Gettextareaselectval is to select the textarea part of the content, you can enter the internal           Self.val (). Length >= Base.totalnum is to remove textarea part of the content, you can re-enter                 if (! (Event.keycode = = 8 | | event.keycode = = 9 | | event.keycode = = | | event.keycode = = Notoginseng | | event.keycode = | | | event.ke Ycode = = 39 | | Event.keycode = = 40 | | Event.ctrlkey && Event.keycode = = 65 | |                            Gettextareaselectval ()) && self.val (). Length >= Base.totalnum) {return false;                        }                        }); Prevents the user from dragging content into the input box after entering all content Self[0].ondrop = function () {if (Self.val (). lengt                            H >= base.totalnum) {return false;                        }                        }; Prevents the user from right-pasting content into the input box Self[0].onpaste = function () {if (Self.val ()) after entering all content.                            Length >= base.totalnum &&!gettextareaselectval ()) {return false;             }                        };           Gets the start and end position of the selected text function getpositions () {var x = 0,                            y = 0, val = self[0].value;                            x = Self[0].selectionstart;                            y = self[0].selectionend;                                return {"Val": Val, "X": X,                        "Y": y};                            }//Gets the text selected in TextArea function Gettextareaselectval () {                                if (window.getselection) {//firefox,chrome,safari,opera etc                            Return Getpositions (). Val.substring (Getpositions (). x, Getpositions (). Y). length > 0;                             } else if (document.selection) {//ie,ie can be obtained directly without taking advantage of start and end position interception   Return Document.selection.createRange (). text.length > 0;                    }}}} if (Self.val () = "") {                Self.prev ("label"). HTML ("");        }} base.checkword (Self[0], fun, 100);    }); },

About JavaScript Real-time display of textarea remaining characters

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.