-1

I want to add EventListener to all input className that will disable space when typing using oninput.

input class="inputX" id="idA"></input>
input class="inputX" id="idB"></input>
input class="inputX" id="idC"></input>
input class="inputX" id="idD"></input>

Im using FOR statement and still nowhere. It can be done if im using getElementById but not with getElementsByClassName/Name and even with querySelectorAll (which I believe there is some code missing).

I found JQuery code but I dont know how to write it back in Javascript.

$(".inputX").keyup(function() {
    $(this).val($(this).val().replace(/\s/g, ""));

Hope someone can help me out ~ Thanks

Manage to disable space when using getElementById (as below), but how to use getElementsByClassName?

document.getElementById("idA").addEventListener("input", myFunction);

function myFunction() {
  var x = document.getElementById("idA");
  x.value = x.value.replace(/\s/g, "");
}  
<input class="inputX" id="idA"></input><br />
<input class="inputX" id="idB"></input><br />
<input class="inputX" id="idC"></input><br />
<input class="inputX" id="idD"></input><br />

1 Answers1

0

First you need to understand the difference between getElementsByClassName and querySelectorAll. First one creates HTMLCollection[] while latter one creates a NodeList[].

HTMLCollection[] cannot be iterated with forEach while NodeList[] can:

const withClassName = document.getElementsByClassName('foo');
const withQuerySelector = document.querySelectorAll('.foo');

console.log(withClassName.forEach);
console.log(withQuerySelector.forEach);
<div class='foo'></div>

Therefore I recommend using document.querySelectorAll() in your case with following code:

const foos = document.querySelectorAll('.foo');

foos.forEach((elem) => {
  elem.addEventListener('keyup', (evt) => {
    console.log(evt.currentTarget.value);
  });
});
<input class='foo' />
<br />
<input class='foo' />
Samuli Hakoniemi
  • 18,740
  • 1
  • 61
  • 74
  • i think im not asking the right question xD. Im trying to applied evenListener to all input class, which disable space in each of input fields. I want all input fields cannot use space when typing.. is it possible? – BlackHaikal Feb 05 '21 at 09:28
  • Done, thanks @Samuli Hakoniemi ^^. Replaced console log with : elem.value = elem.value.replace(/\s/g, "") and its working. – BlackHaikal Feb 05 '21 at 10:17
  • @BlackHaikal yes, I left you some work to do on that so you understand it better what is actually going on :) – Samuli Hakoniemi Feb 05 '21 at 11:02