0

I want to add an event listener to my input class to do some validation.

So here is my code:

<!DOCTYPE html>
<html>
<body>

<input type="text" class="inputs form-control" id="input" tabindex="9" maxlength="2">


<script>

var elements = document.getElementsByClassName("inputs");

input.addEventListener('keyup', (event) => {
  let regEx = /^[0-9a-fA-F]+$/;
  let isHex = regEx.test(event.target.value.toString());
  if(!isHex) {
    elements.value = elements.value.slice(0, -1);
  }
})
</script>

</body>
</html>

So if I do that with id, the code works perfectly but it doesn't work with the class. SO do you know why?

magic bean
  • 787
  • 12
  • 39
  • 1
    Reading [the documentation](https://developer.mozilla.org/en-US/docs/Web/API/Document/getElementsByClassName) is always useful. – Teemu Dec 05 '21 at 17:35

1 Answers1

1

getElementsByClassName returns an HTMLCollection. You have to add the event listener to the first item in it.

<!DOCTYPE html>
<html>
<body>

<input type="text" class="inputs form-control" id="input" tabindex="9" maxlength="2">


<script>

var elements = document.getElementsByClassName("inputs")[0];

elements.addEventListener('keyup', (event) => {
  let regEx = /^[0-9a-fA-F]+$/;
  let isHex = regEx.test(event.target.value.toString());
  if(!isHex) {
    elements.value = elements.value.slice(0, -1);
  }
})
</script>

</body>
</html>

If you want to add the event listener to each item, loop through the HTMLCollection:

<!DOCTYPE html>
<html>
<body>

<input type="text" class="inputs form-control" id="input" tabindex="9" maxlength="2">


<script>

var elements = [...document.getElementsByClassName("inputs")];

elements.forEach(e => e.addEventListener('keyup', (event) => {
  let regEx = /^[0-9a-fA-F]+$/;
  let isHex = regEx.test(event.target.value.toString());
  if(!isHex) {
    elements.value = elements.value.slice(0, -1);
  }
}))
</script>

</body>
</html>
Spectric
  • 30,714
  • 6
  • 20
  • 43
  • 1
    `getElementsByClassName returns an HTMLCollection` - In that case, you are supposed to add the listener to all the elements having a specified class. – Rayon Dec 05 '21 at 17:38