Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check length of field as user types

I have seen this ability over the web and I wasn't quite sure how to search for it, a good example is sending a text message it will say as you are typing:

132/160 - and the 132 counter will increase until you hit your limit.

My question was is it possible to get working with javascript alone, no jQuery library? However if I have to use jQuery I will, perhaps a point to a good tutorial, or maybe it's simpler than that, or even some terms to search for it, Thanks.

like image 883
Dan Samuels Avatar asked Dec 07 '10 21:12

Dan Samuels


1 Answers

Use the oninput event, where supported (all modern browsers, IE 9 and later) and onpropertychange for older Internet Explorers:

var myInput = document.getElementById("myInput");
if ("onpropertychange" in myInput && !("oninput" in myInput)) {
    myInput.onpropertychange = function () { 
        if (event.propertyName == "value")
            inputChanged.call(this, event);
    }
}
else
    myInput.oninput = inputChanged;

function inputChanged () {
    // Check the length here, e.g. this.value.length
}

onkeyup is not a suitable event for handling input, as there is a notable delay between the user entering text and your code noticing the change. A user could even hold the key down (for repeating text on Windows devices), but your code would not handle it.

like image 184
Andy E Avatar answered Sep 28 '22 08:09

Andy E