Domanda

I have this code:

<script type="text/javascript">
var maxLength=10;
function charLimit(el) {
    if (el.value.length > maxLength) return false;
    return true;
}

function characterCount(el) {
    var charCount = document.getElementById('charCount');
    if (el.value.length > maxLength) el.value = el.value.substring(0,maxLength);
    if (charCount) charCount.innerHTML = maxLength - el.value.length;
    return true;
}
</script>

together with this input field:

<input type="text" onKeyPress="return charLimit(this)" onKeyUp="return characterCount(this)" />
<span id="charCount">10</span>

As it is now, it's counting down the characters typed, from 10 to 0. I want to add some code to it, where when the page is loaded, it will show 10 (enter 3 characters minimum), and when those three characters are entered, the text in the ( ) will be gone, and only the number will be left, i.e. 7.

Also, if you erase the entered text, if character count is less than 3, the text in the ( ) to be shown again, i.e. something like this: 8 (enter 3 characters minimum)

Or even better, if it can be made like this:

10 (0 characters entered out of 3 miniumum)
9 (1 characters entered out of 3 miniumum)
8 (2 characters entered out of 3 miniumum)
7

It doesn't need to be the current code I have, suggest other code if you have.

È stato utile?

Soluzione

Because noone wrote an answer, I will write one. (Even if it doesn't look like you tried it yourself.)

function characterCount(el) {
    var charCount = document.getElementById('charCount');
    if (el.value.length > maxLength) el.value = el.value.substring(0,maxLength);
    if (charCount) charCount.innerHTML = maxLength - el.value.length;
    return true;
}

to

function characterCount(el) {
    var charCount = document.getElementById('charCount');
    if (el.value.length > maxLength) el.value = el.value.substring(0,maxLength);
    if (charCount) {
        if(el.value.length < 3) {
            charCount.innerHTML = (maxLength - el.value.length) + ' (' + (3 - el.value.length) + ' out of 3 characters minimum)';
        } else {
            charCount.innerHTML = maxLength - el.value.length;
        }
    }
    return true;
}
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top