With HTML, how to know if all the required inputs are not empty so I can enable the submit button?

Viewed 38

I have a form where I need to check for all of the required inputs if are not empty so I can enable the submit button.

<form id="inquiry-component-form" method="post">
   <input id="inquiry-media-outlet" type="text" name="media_outlet" required>
   <input id="inquiry-name" class="form-control" type="text" name="name" required>

   <button id="submit-inquiry-form" disabled type="submit">Submit</button>
</form>

I tried to do this with jQuery the problem is that it is not possible because of Liquid/Jekyll code runs at build time. So I need to know a way to do this with HTML.

Any ideas on how can I achieve what I need?

2 Answers

You can't do this with just HTML, but you can with CSS.

input[type=text]:not(:valid) ~ button[type=submit] {
  pointer-events: none; /* Disables mouse pointer interactions */
  
  /* Styles to make it look like it's disabled */
  opacity: 0.6;
}
<form id="inquiry-component-form" method="post">
  <input id="inquiry-media-outlet" type="text" name="media_outlet" required>
  <input id="inquiry-name" class="form-control" type="text" name="name" required>

  <button id="submit-inquiry-form" type="submit">Submit</button>
</form>

Explanation:

input[type=text]:not(:valid) ~ button[type=submit] - Select buttons with type submit that are siblings of invalid (:not(:valid)) inputs with type text.

You'll also have to add tabindex="-1" to the button if you want to prevent tabbing-and-entering.

Are you sure the js is run after the document is loaded? All template engines support JS. It is by no means that you can't use JS to do that.

document.addEventListener('DOMContentLoaded', e => {
  const formEle = document.querySelector('#inquiry-component-form')
  const inputEles = formEle.querySelectorAll('input')
  const buttonEle = formEle.querySelector('button')
  formEle.addEventListener('input', e => {
    let filled = Array.prototype.every.call(inputEles, ele => ele.value.length > 0)
    if (filled) {
      buttonEle.removeAttribute('disabled')
    } else {
      buttonEle.setAttribute('disabled', '')
    }
  })
})
<form id="inquiry-component-form" method="post">
  <input id="inquiry-media-outlet" type="text" name="media_outlet" required>
  <input id="inquiry-name" class="form-control" type="text" name="name" required>
  <button id="submit-inquiry-form" disabled type="submit">Submit</button>
</form>

Related