detectar cuando todos los inputs de html tienen valores in javascript

To detect when all inputs in an HTML form have values in JavaScript, you can listen for the submit event of the form and then iterate over all the input elements to check if they have values. Here's an example:

<form>
  <input type="text" name="name">
  <input type="email" name="email">
  <input type="password" name="password">
  <button type="submit">Submit</button>
</form>
167 chars
7 lines
index.tsx
const form = document.querySelector('form');

form.addEventListener('submit', (event) => {
  event.preventDefault(); // prevent the form from submitting

  const inputs = form.querySelectorAll('input');
  let allHaveValues = true;

  // check if all inputs have values
  inputs.forEach((input) => {
    if (!input.value) {
      allHaveValues = false;
    }
  });

  if (allHaveValues) {
    // all inputs have values, do something
  } else {
    // not all inputs have values, show an error message or handle it in some other way
  }
});
539 chars
22 lines

In this example, we first select the form element using document.querySelector. Then we add a submit event listener to the form. Inside the event listener, we first prevent the default behavior of the form using event.preventDefault() so that we can handle the form submission ourselves.

Next, we select all input elements inside the form using form.querySelectorAll('input'). We then iterate over all the inputs using inputs.forEach and set a flag allHaveValues to false if any input element does not have a value.

Finally, we check the value of allHaveValues. If it is true, all input elements have values, and we can do something with the form data. If it is false, we show an error message or handle the situation in some other way.

gistlibby LogSnag