SMS Character counter using javascript and jQuery

When writing multipart sms each sms contain different character count. SMS contain 160 characters, but if you write multipart SMS second SMS will be shorter because it will contain concatenated SMS header. So the receiver will know if the SMS have other part(s). You can find more explanation elsewhere.

Shortly here is the example to count SMS using javascript and jQuery.

<script type="text/javascript" src="http://code.jquery.com/jquery.min.js"></script>
<script>
$(document).ready(function(){

	part1Count = 160;
	part2Count = 145;
	part3Count = 152;

    $('#message').keyup(function(){
        var chars = $(this).val().length;
            messages = 0;
            remaining = 0;
			total = 0;
		if (chars <= part1Count) {
			messages = 1;
			remaining = part1Count - chars;
		} else if (chars <= (part1Count + part2Count)) { 
			messages = 2;
			remaining = part1Count + part2Count - chars;
		} else if (chars > (part1Count + part2Count)) { 
			moreM = Math.ceil((chars - part1Count - part2Count) / part3Count) ;
			remaining = part1Count + part2Count + (moreM * part3Count) - chars;
			messages = 2 + moreM;
		}
        $('#remaining').text(remaining);
        $('#messages').text(messages);
        $('#total').text(chars);
		if (remaining > 1) $('.cplural').show();
			else $('.cplural').hide();
		if (messages > 1) $('.mplural').show();
			else $('.mplural').hide();
		if (chars > 1) $('.tplural').show();
			else $('.tplural').hide();
    });
	$('#message').keyup();
});
</script>

<textarea name="message" value="" id="message"></textarea>
<div>
    <div><span id="remaining">160</span>&nbsp;Character<span class="cplural">s</span> Remaining</div>
    <div>Total&nbsp;<span id="messages">1</span>&nbsp;Message<span class="mplural">s</span>&nbsp;<span id="total">0</span>&nbsp;Character<span class="tplural">s</span></div>
</div>

Good luck.

No Comments

Trackbacks/Pingbacks

  1. count unicode character using jquery | Code and Programming - [...] : http://www.mindrestingplace.com/2012/07/18/sms-character-counter/ This entry was posted in all on December 31, 2012 by [...]

Leave a Reply