Oleg Sapishchuk
Oleg Sapishchuk

Reputation: 657

Textarea limit characters and lines with Javascript

There are some similar topics to this theme, but current requirements are more specific and I couldn't combine it yet with existent solutions, so asking community to help me with. I need to build textarea js validator for rules:

Could you please tell how I could implement this?

p.s. It should be clear Javascript solution

Upvotes: 0

Views: 392

Answers (1)

user6586783
user6586783

Reputation:

This is how your code should look like (see also JSFiddle):

var rows = 4;
var cols = 32;

var body = document.body;
var ta = createElem(body, 'textarea');
var div = createElem(body, 'div');

ta.rows = rows;
ta.cols = cols;

ta.addEventListener('keyup', () => {
  var lines = ta.value.split('\n');

  lines = lines
    .slice(0, Math.min(lines.length, rows))
    .map(line => line.substring(0, cols));

  ta.value = lines.join('\n');
  displayRemaining(cols * rows - ta.value.length + rows - 1);
});

displayRemaining(cols * rows);

function createElem(a, b){
  b = document.createElement(b);
  a.appendChild(b);
  return b;
}

function displayRemaining(a){
  div.innerHTML = 'Characters remaining: ' + a + '.';
}

Upvotes: 1

Related Questions