I have a series of forms on a page which each have a simple text counter on the input element (to illustrate the length of a title as it is being typed). When I was working out how to do the counter it was on a singular instance of the form.
How do I have it so the counter works in relation to the nextElementSibling when there are multiple instances of the form? I would've thought it would be done with e.target property, but I can't work out how to store the input element as a target so to speak? I thought e.target = item in the code below would work but this doesn't.
Codepen: https://codepen.io/thechewy/pen/powZppR
var title = document.querySelectorAll(".image-title-upload"),
charsRemaining = document.querySelectorAll(".image-title-upload").nextElementSibling,
maxValue = 125;
title.forEach((item) => {
item.addEventListener("input", (e) => {
//e.target = item; thought this might work but it doesn't
remaining = maxValue - item.value.length; // work out how many characters are left
charsRemaining.textContent = remaining;
});
});
form {
margin-bottom: 2rem;
}
span {
display: block;
margin-top: 4px;
}
<form>
<input class="image-title-upload" type="text" name="image-title" placeholder="Title">
<span class="tl characters-remaining">125</span>
</form>
<form>
<input class="image-title-upload" type="text" name="image-title" placeholder="Title">
<span class="tl characters-remaining">125</span>
</form>
this way
const
titleInput = document.querySelectorAll(".image-title-upload")
, maxValue = 125;
titleInput.forEach( item =>
{
item.oninput = e =>
{
item.nextElementSibling.textContent = maxValue - item.value.length
}
})
form {
margin-bottom: 2rem;
}
span {
display: block;
margin-top: 4px;
}
<form>
<input class="image-title-upload" type="text" name="image-title" placeholder="Title">
<span class="tl characters-remaining">125</span>
</form>
<form>
<input class="image-title-upload" type="text" name="image-title" placeholder="Title">
<span class="tl characters-remaining">125</span>
</form>
you can also use
e.target.closest('form').querySelector('.characters-remaining').textContent = ....