Reputation: 133
could you please inform how the number of texts can be counted within textarea by pressing "enter".
Textarea can be created like this:
<textarea name="ta1" id="ta1" rows="4" cols="50">
ABC[enter]
DEF[enter]
GHI[enter]
</textarea>
<input type="text" name="textnumber" value="">
Then "textnumber" will show "3" instantaneously. Thanks.
Upvotes: 0
Views: 1352
Reputation: 1084
Try do that in this way
function getEntersCount(textarea, result) {
var text = textarea.value,
enters = text.split(/\r|\r\n|\n/),
count = enters.length;
result.value = count;
}
getEntersCount(
document.getElementById("ta1"),
document.querySelector('[name="textnumber"]')
);
Guess this will help you
EDIT 1
getEntersCount(
document.getElementById("ta1"),
document.getElementById('textnumber')
);
EDIT 2
// Function will take text and return count of lines in it
function getEntersCount(text) {
var enters = text.split(/\r|\r\n|\n/),
count = enters.length;
return count;
}
// Usage example
var count = getEntersCount(document.getElementById("ta1").value)
console.log(count);
Upvotes: 1
Reputation: 18744
To count the number of newlines in the textarea you have to :
get the value of textarea var val = document.querySelector('textarea').value
then count \n
(newline) var res = val.match(/\n/g).length
To bind the result and have it visualized in your input you can wrap this process in a function to be called on every textarea update,
try this:
var tarea = document.querySelector('textarea')
var input = document.querySelector('input')
function update() {
var res = (tarea.value.match(/\n/g)) ? tarea.value.match(/\n/g).length : 0;
// ^^^^^^
// this is a ternary (like a conditional check)
input.value = res;
}
tarea.addEventListener('input', update)
<textarea name="ta1" id="ta1" rows="4" cols="50">
ABC DEF GHI
</textarea>
<input type="text" name="textnumber" value="0">
Upvotes: 0
Reputation: 467
This question has been asked before (see here).
You can use Regex to find the number of newlines in a string.
The pattern to match is: /\n/g
which means the number of occurances of a newline
See this.
Upvotes: 0