How to add multiple id in javascript with eventlistener?

2k Views Asked by At

I have one form with name, last name, phone and other field. all field has unique id and name. Now i have this code for disable type english in field and sho alert to user for change keyboard. but i cant add multiple id to this

Example : i have two field with id > #name and #phone. i want call to this ids like : document.getElementById('name phone') But above code not working and show " cant read property addEventListener".

My code:

    document.getElementById('name').addEventListener('keypress',function(e){

         if ((e.charCode >= 97 && e.charCode <= 122) || (e.charCode>=65 && e.charCode<=90)){
            alert("لطفا فارسی تایپ کنید");
            e.preventDefault();
        }

    });

    function isPersian(str){
        var p = /^[\u0600-\u06FF\s]+$/;
        return p.test(str);
    }
<input type="text" name="firstname" id="name" class="field form-control" placeholder="Your name">
<input type="text" name="lastname" id="inputLastName" class="field form-control" placeholder="Last name">
<input type="tel" name="phonenumber" id="phone" class="field form-control" placeholder="Phone Number">

2

There are 2 best solutions below

0
On BEST ANSWER

You're making some wrong assumptions about how things work.

Firstly, getElementById() does what it says on the tin - it gets an element (singular), not a nodelist. It doesn't accept multiple IDs, it accepts one. Which is why:

document.getElementById('name phone')

or any other means of specifying multiple IDs, will result in the method returning null. You need instead:

document.querySelectorAll('#name, #phone')

However, that returns a nodelist, and addEventListener() is a method of the HTML Element object, not the nodelist object, so you can't run it on there and expect it to bind the event to all elements returned.

You have two options:

1 Iterate over the nodelist and bind the event to each element

2 Use event delegation

document.addEventListener('keypress', function(e) {
    if (!e.target.matches('#name, #phone')) return;
    //your code here
});
0
On

Use querySelectorAll, forEach to add events

document.querySelectorAll("#name, #inputLastName, #phone").forEach((ele) => {
  ele.addEventListener("keypress", function (e) {
    if (
      (e.charCode >= 97 && e.charCode <= 122) ||
      (e.charCode >= 65 && e.charCode <= 90)
    ) {
      alert("لطفا فارسی تایپ کنید");
      e.preventDefault();
    }
  });
});

function isPersian(str) {
  var p = /^[\u0600-\u06FF\s]+$/;
  return p.test(str);
}
<input type="text" name="firstname" id="name" class="field form-control" placeholder="Your name">
<input type="text" name="lastname" id="inputLastName" class="field form-control" placeholder="Last name">
<input type="tel" name="phonenumber" id="phone" class="field form-control" placeholder="Phone Number">