lundi 7 janvier 2019

How to disable/enable submit button depending on checkbox state?

There's a form with two text fields and one checkbox, all of them are required and have the required attribute.

The submit button should only get enabled if the required inputs are filled and checked.

With the current code the text field validation seems to work fine however it doesn't have an effect on the checkbox.

Jsfiddle: https://jsfiddle.net/2qu9ojp1/

<form action="#otherForm">
   Name * <input name="otherForm-name1" placeholder="required" required> <br />
   Tel * <input name="otherForm-surname" placeholder="required" required> <br />
   <input type="checkbox" name="otherForm-chcekbox" required><label for="otherForm-chcekbox">I agree</label> <br />
   <button id="otherForm-submitBtn" class="monitored-btn" type="submit">Submit</button>
</form>

<script>
const inputSelector = ':input[required]:visible';
  function checkForm() {
  // here, "this" is an input element
  var isValidForm = true;
  $(this.form).find(inputSelector).each(function() {
   if (!this.value.trim()) {
    isValidForm = false;
   }
  });
  $(this.form).find('.monitored-btn').prop('disabled', !isValidForm);
  return isValidForm;
  }
$('.monitored-btn').closest('form')
  // in a user hacked to remove "disabled" attribute, also monitor the submit event
  .submit(function() {
    // launch checkForm for the first encountered input,
    // use its return value to prevent default if form is not valid
    return checkForm.apply($(this).find(':input')[0]);
   })
   .find(inputSelector).keyup(checkForm).keyup();
</script>




Aucun commentaire:

Enregistrer un commentaire