Adding Counter to HTML Form and Calculate Credits

邮差的信 提交于 2019-12-11 05:55:45

问题


I have a simple HTML Form that allows the user to enter some text which is then sent as an SMS/TXT Message via an SMS Gateway. The user enters the message text into a textarea:

<textarea rows="10" cols="40" id="smsbody" validate = "required:true" name="MessageBody"></textarea>

They can enter as little or as much text as they like, however as each SMS is limited to 160 characters I would like to display a character counter that shows both the number of characters entered and then also calculates how many SMS credits this will use. The formula for calculating the credits is based on the total number of credits entered: if a message exceeds 160 characters, it will be split into multiple message parts. Each message part is restricted to 153 characters in length (7 bytes for headers). So a message of 160 characters will be 1 credit, 306 characters will be 2 credits, 459 characters will be 3 credits and so on.

Ideally I would like this to appear in this format:

0 characters, 1 SMS message(s) 200 characters, 2 SMS message(s)

I'm already using jQuery so happy to use a jQuery based solution as well.

Many thanks, Steve


回答1:


Something like this?

Try it out: http://jsfiddle.net/kG8U2/2

I think I understand correctly in that for 1 message, it can be 160 characters, but for more than one, the number of messages is characters divided by 153.

HTML

<textarea rows="10" cols="40" id="smsbody" validate = "required:true" name="MessageBody"></textarea>
<div id='message'>
    <span id='char'>0</span> characters,
    <span id='msgs'>0</span> SMS message(s),
    <span id='remg'>160</span> remaining
</div>​​​​

jQuery

var $chars = $('#char');
var $msgs = $('#msgs');
var $remg = $('#remg');

$('#smsbody').keyup(function(evt) {
    var len = this.value.length;
    $chars.text(len);
    if(len <= 160) {
        $msgs.text(1);
        $remg.text(160 - len);
    } else {
        var multi = Math.ceil((len/153)) ;
        $msgs.text(multi);
        $remg.text((multi * 153) - len);
    }
});​

EDIT: Fixed a flaw where it was off by 1 character, and added a remaining counter for fun.



来源:https://stackoverflow.com/questions/3237164/adding-counter-to-html-form-and-calculate-credits

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!