I'm working with Bootstrap
and the CKEditor5 Classic
.
I want to have a counter with ONKEYUP
in my textarea
which should be shown each time the key goes up in div id countThis
..
I only need pure javascript I've tried following but it doesnt work..
How can I make it work? thank you!
(I need it without jQuery!)
CODE
<div class="row">
<div class="form-group col-10">
<label class="form-label" for="txt">Ddscription</label>
<textarea id="txt" class="form-control" onkeyup="CheckInput()"></textarea>
</div>
<div class="col-2 mt-4" id="countThis"></div>
</div>
ClassicEditor
.create(document.querySelector('#txt'))
.catch(error => {
console.error(error);
});
function CheckInput() {
var value = document.getElementById("txt").value.length;
console.log(value); // HERE COMES NOTHING
document.getElementById("countThis").innerHTML = value;
}
CodePudding user response:
I suggest to capture the event using CKEditor API instead of the keyup attribute, in this way:
ClassicEditor
.create(document.querySelector('#txt'))
.then(editor => {
/// Register change listener
editor.model.document.on( 'change:data', () => { /// <--- Changes listener
/* ALL THE LOGIC IS DOWN HERE */
document.getElementById("countThis").innerHTML =
editor /// <--- Editor reference
.getData() /// <--- Editor content
.replace(/<[^>]*>/g, '') /// <--- Convert HTML to plain text
.replace(' ', ' ') /// <--- Remove for spaces
.length; /// <--- Get plain text length
});
})
.catch(error => {
console.error(error);
});
<script src="https://cdn.ckeditor.com/ckeditor5/30.0.0/classic/ckeditor.js"></script>
<div class="row">
<div class="form-group col-10">
<label class="form-label" for="txt">Ddscription</label>
<textarea id="txt" class="form-control"></textarea>
</div>
<div class="col-2 mt-4" id="countThis"></div>
</div>
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>