user965748
user965748

Reputation: 2387

Textarea input length check in JavaScript

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);
}

Upvotes: 1

Views: 57

Answers (1)

Jimmie Tyrrell
Jimmie Tyrrell

Reputation: 1658

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>

Upvotes: 1

Related Questions