问题
I have a text field to type sms message both in english and chinese language. As I have searched, 1 sms can only have 1120 bits. Each english character is 7 bit so it can be 1120/7 = 160 characters and for chinese each character is 16 bits so that is 1120/16 = 70 characters. I need to use jquery to show the words written and words remaining under the text field. how do i do this?
回答1:
Characters can be single byte ,double byte, triple byte and so on. So single byte follows in a particular range.Same thing is true for other characters.Based on this I have created following functions that will calculate the size of a string on the basis of memory
function getByteLength(normal_val) {
// Force string type
normal_val = String(normal_val);
var byteLen = 0;
for (var i = 0; i < normal_val.length; i++) {
var c = normal_val.charCodeAt(i);
byteLen += c < (1 << 7) ? 1 :
c < (1 << 11) ? 2 :
c < (1 << 16) ? 3 :
c < (1 << 21) ? 4 :
c < (1 << 26) ? 5 :
c < (1 << 31) ? 6 : Number.NaN;
}
return parseInt(byteLen)*8;
}
I have created a js fiddle that will work for you. http://jsfiddle.net/paraselixir/d83oaa3v/6/
回答2:
have a look at below snippet, this counts total characters and total number of message.
you can change the value of $maxVal
to 160/70
$(document).ready(function () {
var $remaining = $('#charNum'),
$messages = $remaining.prev();
$maxVal = 160;
$('.word-counter').keyup(function(){
var chars = this.value.length,
messages = Math.ceil(chars / $maxVal),
remaining = messages * $maxVal - (chars % (messages * $maxVal) || messages * $maxVal);
$remaining.text(remaining + ' characters remaining');
$messages.text(messages + ' message(s) / ');
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<textarea name="" id="SMSMessage" cols="30" rows="2" class="form-ctrl word-counter foo-value"></textarea>
<span class="error-message word-counter">0 message(s) / </span><span id="charNum" class="error-message">160 characters remaining</span>
回答3:
there is a package that we can use for this issue, checkout: https://github.com/danxexe/sms-counter
来源:https://stackoverflow.com/questions/42709994/jquery-sms-character-calculator-with-7-bit-and-16bit