1

I'd like to create an SMS gateway which alerts the user each time when 160 chars are written (or pasted). I need to store a variable n containing number of message parts of 160 chars. The code will be like this, just the n needs to be stored globally. Is there any better way than e. g. storing it into a hidden form field? Note: an assumption that less than 160 chars will be pasted at once is safe in this particular case.

window.onload = function() {
  var n=1;   
  var t=document.getElementById('msg');
  t.addEventListener('input', function() {
    var l=t.value.length;
    if(l>n*160){
      n++;
      alert('Message will be split into '+n+' parts');   
    }
  }, false);
}
2
  • That depends on what you want to do with n after you've calculated it. Do you want to submit it along with the textarea's contents? Commented Apr 29, 2015 at 20:41
  • Well, looks like it's actually a working solution, I probably overlooked something before. Commented Apr 29, 2015 at 20:46

1 Answer 1

1

As mentioned in my comment, it depends on what you want to do with n ultimately.

If you just want it to show the user a message, you can update the DOM once you've calculated this value.

Your current example doesn't allow the user to delete text after they've typed/pasted it in. A better example would be stateless, i.e. don't compare n to itself, as in my example below:

var t = document.getElementById('msg');
var splitSize = 10;
var n = 1;
t.addEventListener('input', function() {
  var nextN = 1;
  
  if (t.value.length > 0) {
    nextN = Math.ceil(t.value.length / splitSize);
  }
  
  if (n !== nextN) {
    n = nextN;
    var label = document.getElementById('label');

    if (n === 1) {
      label.innerHTML = '';
    } else {
      label.innerHTML = 'The message will be split into ' + n + ' parts';
    }
  }
});
<p id="label"></p>
<textarea id="msg"></textarea>

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.