Beaniie Beaniie - 1 year ago 76
Javascript Question

Form element Iteration, in Javascript

I've been working on a code snippet for a template module that I have been creating and I've hit a wall so to speak. I'm trying to loop through all textareas on my page, and apply formatting with some very basic validation.

Javascript is not my strongest suit but I can understand it to a point, my question is how do I collect the ID's and then use them to apply the formatting.

For example,

for each (textarea)
collect character restriction from html
display character restriction in a formatted manner

I have included my JSFiddle which I have been using to build this snippet.

Answer Source

I've based on @FodorZoltán's class. My class does now:

  • append the counter below the textarea;
  • position the counter in the below part of the textarea;

Yeah, I'm lazy and the code has grown up. I added some events and renamed the class name to "TextAreaRanger". It's working here:

var TextAreaRanger = function(input) {

    this.MAX = parseInt(input.getAttribute('maxlength'));
    this.INPUT = input;

    // add input events
    input["oncut"] =
    input["onpaste"] =
    input["onkeydown"] =
    input["onkeyup"] = this.update.bind(this);

    // create wrapper element
    this.wrapper = document.createElement('div');
    this.wrapper.innerHTML = 'Chars left: '+ (this.MAX - input.value.length);

    /* input parent element */
    var ipar = input.parentNode;

    // find input's i
    for (var i = 0, el; el = ipar.children[i]; i ++) {
        if(el === input) break;

    // append wrapper below the input
    if (ipar.children[++i]) {
        ipar.insertBefore(this.wrapper, ipar.children[i]);
    } else ipar.appendChild(this.wrapper);

    /* stylize wrapper */ = "relative"; = '#f00'; = '11px'; = (input.offsetLeft + (input.offsetWidth - 100)) + "px"; = (-parseInt( * 2) + "px";

// Update the counter
TextAreaRanger.prototype["update"] = function() {
    this.wrapper.innerHTML = 'Chars left: ' + (this.MAX - this.INPUT.value.length);
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download