HiveBrain v1.2.0
Get Started
← Back to all entries
patternjavascriptMinor

Updating a textarea label with the number of characters inside the field itself

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
itselffieldthenumberwithupdatingcharacterstextarealabelinside

Problem

How would you improve and shorten this small piece of code? It basically update a textarea label with the number of characters inside the field itself. It saves the original label and restores it when characters count is 0.

jsFiddle here while sprintf is from here.

$('#send_sms_content').keyup(function() {

    // The label and characters count of textarea
    var label = $(sprintf('label[for="%s"]', $(this).attr('id'))),
        count = $(this).val().length;

    // Make backup of label original html into "data-original-value" attribute
    if($.type(label.attr('data-original-value')) === 'undefined') {
        label.attr('data-original-value', label.html());
    }

    // When empty textarea then restore the orignal label
    if(count == 0) {
        label.html(label.attr('data-original-value'));
        return;
    }

    // Regular expression to match any digit in the label
    var digit = new RegExp("[0-9]+")

    // If there are no digits in the label append the count
    if(!digit.test(label.html())) {
        label.html(label.html() + ' ' + sprintf('(%s)', count));
    }
    else { // There are digits already, replace with the new count
        label.html(label.html().replace(digit, count));
    }

});

Solution

Just a few things I notice, prolly not warranting a "mark as answer" but may help:

  • Cache $(this): var $this = $(this); So that you don't keep inefficiently re-wrapping this



  • $(this).attr('id') - really? You can just use this.id, you know.



  • hasDigit === digit, so why do you have both? Scrap one of those regexes, the other one is redundant.



  • Cache label.html() so that you don't keep grabbing it (which is quite inefficient). Instead: var labelHtml = label.html() and then reuse labelHtml

Context

StackExchange Code Review Q#10407, answer score: 4

Revisions (0)

No revisions yet.