Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Display a limit counter of an input length

Tags:

jquery

I use the below jquery to limit the length of an input to 110 characters. Supplementary, it displays how many characters was inputted, but I want to display how many characters are left. Any help? Also, I will appreciate any suggestions about how to improve this code.

jQuery(document).ready(function(){
    jQuery("#post_title").prev("label").children(".adverts-form-required").after("<span class=\"title-counter\">(<input type=\"text\" value=\"0\" maxlength=\"3\" size=\"3\" id=\"title_counter\" readonly=\"\" style=\"background:#fff;\">)</span>");
    jQuery("#post_title").keyup( function() {
        jQuery("#title_counter").val(jQuery("#post_title").val().length);
    });
    jQuery(".adverts-field-text #post_title").keyup( function() {
        var $this = jQuery(this);
        if($this.val().length > 110)
            $this.val($this.val().substr(0, 110));
    });
});

The input field:

<div class="adverts-control-group adverts-field-text">
    <label for="post_title">Title
        <span class="adverts-form-required">*</span>
    </label>
    <input name="post_title" id="post_title" type="text">
</div>

UPDATE

Updated the code, thanks to @dhaval-marthak. It works. The question is how to display an default information about the length limit in the <span class="title-counter"></span> tag when the input length is equal to 0? I tried this: <span class="title-counter">\(the input limit is 110 characters\)</span>, but it is not displayed again when I delete the inputted text.

# add a span tag to display the counter
jQuery("#post_title").prev("label").children(".adverts-form-required").after("<span class=\"title-counter\"></span>");

# add an input length limit
jQuery("#post_title").keypress(function(){
    if(this.value.length > 110){
        return false;
    }
    jQuery(".title-counter").html("are left: " +(110 - this.value.length) +" characters");
});
like image 395
Iurie Avatar asked Nov 26 '25 21:11

Iurie


1 Answers

Just set your limit in the HTML? It will be overwritten by the counter. Then when the textarea is empty, reset the HTML.

Based on @dhaval-marthak's answer:

HTML

<textarea></textarea>
<span id="remaining"></span>
<span id="limit">(the input limit is 110 characters)</span>

Javascript

$('textarea').keyup(function () {
    if (this.value.length === 0) {
        $('#limit').show();
        $('#remaining').hide();
    } else {
        $('#limit').hide();
        $('#remaining').show();
    }

    if (this.value.length > 110) {
        return false;
    }

    $("#remaining").html("Remaining characters : " + (110 - this.value.length));
});

Updated Fiddle: http://jsfiddle.net/r34gM/185/

like image 132
Gerrit Bertier Avatar answered Nov 29 '25 14:11

Gerrit Bertier



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!