** Update **
Modified the code for Ricardo Lohmann’s suggestion with the additional modification of using val() instead of text().
It is still not correct, but is a whole lot more consistent. Initially, it is off by 1 character, and is progressively off by an additional 1 character for every enter key pressed in the text area. I’m not sure yet whether the text area is returning for it yet, but it is not a CRLF.
I think that is the main problem. I will do some testing on carriage returns and line feeds being passed to the SMS processor, and hope that I can convert it after the fact.
Parsing through the textarea value and adding 1 character to the count for every “enter key” pressed will get the value I am after.
If anyone has ideas on how to get the textarea to use a full CRLF, I’m all ears.
I’m allowing managers to create SMS messages and need to show them how many characters are in use. So far the number of characters is off by 1 when I start and then becomes wildly inaccurate over time.
<textarea id="message_content"></textarea>
<div id="message_length"></div>
The message content is initially set with Javascript.
uri_decoded = 'Test Message\r\nTest Message';
Selecting all the text with select-all and throwing into a text editor like Notepad++ shows 26 characters, which is correct. 22 for characters, 2 for white space, and 2 for the CRLF.
The following code shows 25 characters initially, and then just fails to represent it accurately at all:
// Dynamically update the SMS length when keys are pressed
$("#message_content").keypress(function(e){
var string_length = $("#message_content").text().length + 1;
var message_count = string_length / 160;
message_count = Math.ceil(message_count);
var html = '';
html = html + message_count + ' message(s) - ' + string_length + ' characters';
$("#message_length").html(html);
});
// Dynamically update the SMS length when the textarea blurs
$("#message_content").blur(function(){
var string_length = $("#message_content").text().length;
var message_count = string_length / 160;
message_count = Math.ceil(message_count);
var html = '';
html = html + message_count + ' message(s) - ' + string_length + ' characters';
$("#message_length").html(html);
});
// Perform an initial update on the character count
$("#message_content").blur();
Now on the keypress function I have added 1 to the length since AFAICT the event does not have access to the content with the new character added. In any case, the event does not fire initially, and I am evaluating the blur event primarily.
I chose textarea because it accurately represents the CRLF being passed from the database, that is ultimately passed to the SMS processor.
Any help or observations are appreciated in obtaining accurate values.
Fix the following problems:
var string_length = $("#message_content").text().length + 1;return 1 if there’s no text demo.
Use
keyupinstead.You can use the same come on both events.