asked on
Count textual content of a div - Javascript
Hi All,
The following should check the textual length of a DIV with editable content. However, even though it is set to 10 chars it actions at 1 chars, and when I delete all the chars from the div it does not return it to the first state. Any ideas:
function LenCheckURL()
{
if (document.getElementById("editable").innerText > 10 )
{
document.getElementById("hid_URL_OK").value = 0;
document.getElementById('Icon8').src = "../../Local_Config/Skins/JS_Default/Gen_CP_Images/Yellow_2.gif";
}
else
{
document.getElementById("hid_URL_OK").value = 1;
document.getElementById('Icon8').src = "../../Local_Config/Skins/JS_Default/Gen_CP_Images/Yellow_2G.gif";
}
CheckFormParts();
}
-----------------------------------------------------------------------
<div id="editable" contenteditable="true" class="txtTitle_URL" onkeypress="LenCheckURL();" ></div>
ASKER
It still actions on the first char not the 10th
A
You have 3 parts to your function
function ... () {
if (text is > 10) {
// part I
} else { // text <= 10) {
// part II
}
CheckFormParts(); // Part III
}
Part I fires if text > 10.Part II fires if text <= 10
Part III fires regardless
ASKER
I like your solution framework. However, I can't replicate it locally and must be missing something.
I have this:
---------------------------------------------------------------------------------------
<!doctype html>
<html>
<head>
<script language="javascript">
const max = 10;
const path = "../../Local_Config/Skins/JS_Default/Gen_CP_Images/";
const CheckFormParts = () => {}
const hid = document.getElementById("hid_URL_OK");
document.getElementById("editable").addEventListener("keyup",function(e) {
hid.value = "";
const len = this.textContent.length;
if (len > 0) {
const moreThanMax = len > max;
hid.value = moreThanMax ? 0 : 1;
document.getElementById("Icon8").src = path + (moreThanMax ? "Yellow_2.gif" :"Yellow_2G.gif");
}
});
</script>
</head>
<body>
<div id="editable" contenteditable="true" class="txtTitle_URL" ></div>
<input id="hid_URL_OK" />
<img id="Icon8" />
</body>
</html>
Many thanks
Abiel M de Groot
ASKER
Sorry, the CheckFormParts() doesn't matter. I want it to either do action part one or part 2 depending on whether there are 10 chars or not.
Either copy the script to just before the </body> OR wrap the whole thing in
window.addEventListener("load",function() {
// code here
});
https://jsfiddle.net/mplungjan/w160r7ty/
ASKER
Got this working by simply changing > (greater than) < Less than
if (document.getElementById("editable").innerText.length < 10 )
And changing the event handler to oninput rather than onkeypress.
Kind regards to all.
A