event listener working with getElementByID but not with querySelectorAll

as per the post title, I have these scripts:

let campolim = document.getElementById("province");

campolim.addEventListener("keyup", () => {
  if (campolim.value.length > 3) {
    campolim.value = campolim.value.slice(0, 3);
  }
});
//----------------------------------------------------//
let campilim = document.querySelectorAll("limitme");
for (var i = 0; i < campilim.length; i++) {
  campilim[i].addEventListener("keyup", () => {
    if (campolim[i].value.length > 3) {
      campolim[i].value = campolim[i].value.slice(0, 3);
    }
  });
}

The scripts should do the same thing (limit the input filds to 3 chars). The first one is working properly, but if I want to capture all fields with limitme class, the script returns that cannot find the length of a unknown element.

Why? What am I missing? This is the html:

<input type="text" class="limitme form-input" id="province" name="province" value="" placeholder="provincia" required="">

<input type="text" class="limitme form-input" id="cap" name="cap" value="" placeholder="cap" required="">

<input type="submit" >

Thanks.

2 answers

  • answered 2019-10-15 15:56 user3587856

    I think it was just a typo in campilim (campolim)

    let campolim = document.getElementById("province");
    
    campolim.addEventListener("keyup", () => {
      if (campolim.value.length > 3) {
        campolim.value = campolim.value.slice(0, 3);
      }
    });
    //----------------------------------------------------//
    let campilim = document.querySelectorAll(".limitme");
    console.log(campilim)
    for (let i = 0; i < campilim.length; i++) {
      campilim[i].addEventListener("keyup", () => {
        if (campilim[i].value.length > 3) {
          campilim[i].value = campilim[i].value.slice(0, 3);
        }
      });
    }
    

    The code works fine with typo fixed.

  • answered 2019-10-15 16:06 behroz

    u replace second section of your code with

     let campilim = document.querySelectorAll(".limitme");
                for (var i = 0; i < campilim.length; i++) {
                    campilim[i].addEventListener("keyup", (e) => {
                       let element=e.currentTarget;
                        if (element.value.length > 3) {
                            element.value = element.value.slice(0, 3);
                        }
                    });
                }
    when use addEventListener in input parameter send e for event and use in function for detect change . for find what is source element u must use e.currentTarget code.