Character countdown like on twitter

后端 未结 9 959
栀梦
栀梦 2020-12-02 06:54

How can I make a \"remaining characters\" countdown like the one on Twitter with jQuery? And also limit the input to a textarea.

9条回答
  •  北荒
    北荒 (楼主)
    2020-12-02 07:28

    It's a suicide to use jQuery, Mootools or similar for such simple task ... unless you are already using them for something else.

    Simple javascript function:

    function limitTextCount(limitField_id, limitCount_id, limitNum)
    {
        var limitField = document.getElementById(limitField_id);
        var limitCount = document.getElementById(limitCount_id);
        var fieldLEN = limitField.value.length;
    
        if (fieldLEN > limitNum)
        {
            limitField.value = limitField.value.substring(0, limitNum);
        }
        else
        {
            limitCount.innerHTML = (limitNum - fieldLEN) + ' charachter(s) to go.';
        }
    }
    

    The first parameter is id of the input/textarea. The second - id of the div to display characters left. The third is the limit itself.

    And simple HTML:

    
    
    100 charachter(s) to go..

提交回复
热议问题