Javascript function Locks all input fields

Asked

Viewed 70 times

-2

I need a help, I set up a function to lock the space be keyboard on the first element of input

would like to have the function run in all fields, but it only blocks in the first field the other fields the function does not work.

var input = document.querySelector('input');
    
  input.addEventListener("keypress", function(e) {
    if (this.selectionStart === 0) {
        if (e.which === 32 ) {
            e.preventDefault();
        }
    }
});
<input type="text" id="campo1">
  <input type="text" id="campo2">
  <input type="text" id="campo3">

  • 1

    querySelector only returns an element; if you need all use querySelectorAll.

  • when I use querySelectorAll function does not work in any field

  • 1

    Yes, please read the documentation for this function to understand how it works: https://developer.mozilla.org/en-US/docs/Web/API/Document/querySelectorAll

1 answer

2


Using the querySelector, you will be applying the rule only to the first element found in the DOM.

Grab all elements using the function querySelectorAll that will return an array with all the selected elements, then just go through these elements and apply the rule to the character lock.

let input = document.querySelectorAll('input');

//console.log(input)

    input.forEach(el => {
      el.addEventListener("keypress", function(e) {
          if (this.selectionStart === 0) {
              if (e.which === 32 ) {
                  e.preventDefault();
              }
          }
      });
    })
<input type="text" id="campo1">
  <input type="text" id="campo2">
  <input type="text" id="campo3">

  • thank you very much , for the help...

Browser other questions tagged

You are not signed in. Login or sign up in order to post.