I have some HTML:
<input type="text" />
and I'm trying to make it so that when the character limit hits 12 that javascript automatically deletes the next character from the input field. See code pen here: https://codepen.io/jadedeterville/pen/NWayzpM
Here is my JS:
inputEl.addEventListener("keyup", fixLength);
function fixLength() {
const inputElValue = inputEl.value.length;
if (inputElValue > 11) {
inputEl.innerHTML.slice(12);
}
}
I also tried inputEl.slice(12); and inputElValue.slice(12);but both of those tell me that .slice isn't a function. I tried adding the toString() but that didn't work either.
Appreciate some advice. I've been looking at this for a long time.
Thank you in advance!
try below code.
if (inputElValue > 11) {
inputEl.value = inputEl.value.slice(0,12);
}
There are three mistakes in your script:
inputEl.innerHTML.slice(12); you're slicing anything from the start of the string up to index 12. So essentially you're clearing the whole string. If you want to keep a specific part of a string it's better to use string.substr(startIndex, length)<input> textbox e.g. inputEl.innerHTML=inputEl.innerHTML.slice(12);.value property instead of .innerHTML as the latter will come up empty.Putting it all together:
let inputEl = document.getElementById("inp");
inputEl.addEventListener("keyup", fixLength);
function fixLength() {
const inputElValue = inputEl.value.length;
if (inputElValue > 11) {
inputEl.value = inputEl.value.substr(0, 12);
}
}
<input type="text" id="inp" />