-2

I have a text area, and I want to display the number of lines in real time. So I came up with these code

    
    var count = document.getElementById('ccs').value.split("\n").length;
    document.getElementById("count").innerHTML = count;
 <p id="count"></p>
<textarea class="" id="ccs" rows="15" wrap="off" style="resize: none; overflow: auto; width:100%" placeholder="Text"></textarea>

How do I loop my script?

Arthur
  • 4,870
  • 3
  • 32
  • 57

2 Answers2

2

This works:

// assigning variables to DOM elements
var $css = document.getElementById('ccs');
var $count = document.getElementById('count');

// adding listener to <textarea id="css"> that is saved
// on $css variable, this listener will execute a 
// anonymous function everytime that the input event on
// textarea has been done
$css.addEventListener('input', function() {
  // inserting on <p id="count"> using $count variable
  // as html the content of:
  // 1. "this" is refering to $css
  // 2. ".value" is taking the current textarea value as string
  // 3. ".split('\n')" is splits the current string value  
  // into substrings using ("\n") as separator to 
  // determine where to make each split.
  // 4. ".length" is counting substrings
  $count.innerHTML = this.value.split("\n").length
})
<p id="count"></p>
<textarea class="" id="ccs" rows="15" wrap="off" style="resize: none; overflow: auto; width:100%" placeholder="Text"></textarea>
Christian Carrillo
  • 2,751
  • 2
  • 9
  • 15
  • Your answer as been accepted but you just put code on it. Please add some explanation to create a valid stack answer – Arthur Aug 05 '19 at 13:15
1

You have to use Javascript Events in order to call a function everytime something append (When textarea's value is updated)

document.addEventListener("DOMContentLoaded", function(event) { 
  
  // Get refs
  const textarea = document.getElementById('ccs')
  const count = document.getElementById("count")
 
  // Define a function
  const countLines = () => {
    var lines = textarea.value.split("\n").length;
    count.innerHTML = lines;
  }
  
  // Call it on start
  countLines();
  // Call it everytime textarea's value change
  textarea.addEventListener('change', countLines);

})
<p id="count">-</p>
<textarea class="" id="ccs" rows="15" wrap="off" style="resize: none; overflow: auto; width:100%" placeholder="Text"></textarea>
Arthur
  • 4,870
  • 3
  • 32
  • 57