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...

问题:

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

<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>

回答1:

I would do this very similarly to Kubwimana Adrien's answer with initially rendering a disabled button.

Also, generally, it is not considered secure to set initial state of validation booleans to TRUE. Thus, changing the code a little.

    const inputSelector = ':input[required]:visible';

    function checkForm() {
        // here, "this" is an input element
        var isValidForm = false;
        $(this.form).find(inputSelector).each(function() {
            if (((this.type != 'checkbox') && (this.value.trim() != "")) || (this.type == 'checkbox' && this.checked)) {
                isValidForm = true;
            }
            else{
            	isValidForm = false
                return false //break out of each loop
            }
        });
        $(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).on("keyup change", checkForm);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<body>
  <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" disabled>Submit</button>
  </form></body>


回答2:

CSS only required

#otherForm-submitBtn {
  enabled: false;
  color: grey;
}

input[type='checkbox']:checked ~ #otherForm-submitBtn {
  enabled: true;
  color: black;
}
<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>


回答3:

Keyup event won't work on a checkbox also it's better to check for checked prop instead of value on a checkbox. Try this:

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() || (this.type == 'checkbox' && !this.checked)) {
      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).on("keyup change", checkForm);

回答4:

You need to check that condition in everytime user type or click checkbox , and toggle disable by removeAttr and attr ..

$("form input").keyup(check);
$("form input:checkbox").on("click", check);

function check() {  
 if($("input[name='otherForm-name1']").val() != "" &&
   $("input[name='otherForm-surname']").val() != "" &&
   $("input[name='otherForm-chcekbox']").prop("checked") == true) {
     $("#otherForm-submitBtn").removeAttr("disabled");
     return;
   }
   $("#otherForm-submitBtn").attr("disabled",true);
   
  
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<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" id="otherForm-chcekbox" required><label for="otherForm-chcekbox">I agree</label> <br />
   <button id="otherForm-submitBtn" class="monitored-btn" type="submit" disabled>Submit</button>
</form>


回答5:

Disable the button with disable attribute. Then listen for the checkbox change event, and either remove the attribute or add it.

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



$(".otherForm-chcekbox").change(function() {
    if(this.checked) {
      if (checkForm()) {
        $("otherForm-submitBtn").removeAttr("disabled");   
      }
    } else {
      $("otherForm-submitBtn").attr("disabled", "disabled");   
    }
});

  • 发表于 2019-01-09 05:18
  • 阅读 ( 239 )
  • 分类:网络文章

条评论

请先 登录 后评论
不写代码的码农
小编

篇文章

作家榜 »

  1. 小编 文章
返回顶部
部分文章转自于网络,若有侵权请联系我们删除