Search code examples
javascriptmagentoprototypejs

Add a character count to admin inputs and textareas


I'd like to add a character count to every input and text area in the product details page in my Magento store admin.

I'm used to jQuery but would rather use the default Prototype library for this if possible. I found this code somewhere which does the trick for the short description and description fields specifically, using their ID's to target them:

Event.observe(window, 'load', function() {

Element.insert( $('short_description').up().next().down('span'), { 
    'after': "<div id='short_description_counter'>Char count: <span id='short_description_counter_num'>"+$('short_description').getValue().length+"</span></div>"
});
Element.insert( $('description').up().next().down('span'), { 
    'after': "<div id='description_counter'>Char count: <span id='description_counter_num'>"+$('description').getValue().length+"</span></div>"
});

Event.observe('short_description', 'keyup', function(event) {   $("short_description_counter_num").update(this.getValue().length);  });
Event.observe('description', 'keyup', function(event) { $("description_counter_num").update(this.getValue().length);    });
});

Can someone with Prototype experience tell me how to edit this so that it runs on every input and textarea, so not specifying an ID? I'm presuming there's some each(function) that can be used.

UPDATE: Here's the current code working on a textarea, specified by it's ID - http://jsbin.com/isisur/2/edit


Solution

  • My prototype is rusty but I think this will work:

    Event.observe(window, 'load', function() {
        $$('input[type="text"], textarea').each( function(i) {
            var my_id = $(i).readAttribute('id');
            $(i).insert({ 
                'after': "<div id='"+my_id+"_counter'>Char count: <span id='"+my_id+"_counter_num'>"+$(i).getValue().length+"</span></div>"
            });
            $(i).observe('keyup', function(e) {
                $(my_id+"_counter_num").update($(this).getValue().length);
            });
        });
    });
    

    JSFiddle