by
back

jquery character count script

It is easy to count characters in a textfield with jQuery:

count characters in a textfield

$(document).ready(function(e) {
    $(".js-count").keyup(function count(){
        $(".js-counter").html($(this).val().length);
    });
});

If we modify the code, we can use it even multiple times on one page

improved version

$(document).ready(function(e) {
    $(".js-count").keyup(function count(){
        var counter = $(this).val().length;
        var target = $($(this).data("target"));
        target.html(counter);
    });
});

html code

<div class="form-group">
    <label for="field1">Field1 <span class="js-target1">0</span>/100</label>
    <input type="text" name="field1" class="js-count" data-target=".js-target1" />
</div>

<div class="form-group">
    <label for="field2">Field2 <span class="js-target2">0</span>/200</label>
    <input type="text" name="field2" class="js-count" data-target=".js-target2" />
</div>


comments powered by Disqus