如果选中了任何复选框,如何启用提交按钮,如果没有选中复选框,则如何禁用它?

时间:2019-10-20 11:13:27

标签: javascript jquery html

如何在选中任何复选框的情况下启用提交按钮,而在未选中任何复选框的情况下如何禁用提交按钮?

$('.1').change(function(){
 
  form_valid = false;
  if($('.1').prop('checked')==true){
   
    $('#submit-btn').attr('class','btn btn-primary');
    form_valid = true;
  }
  else{
    
    form_valid = false;
  }

});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="checkbox" name="electronic[]" value="101" class="1"> fan<br>
<input type="checkbox" name="electronic[]" value="102" class="1"> tv<br>
<input type="checkbox" name="electronic[]" value="103" class="1"> ac<br>
<input type="checkbox" name="electronic[]" value="104" class="1"> mobile<br>

2 个答案:

答案 0 :(得分:0)

 function check(){
 
  $('input[type=checkbox]').each(function () {
  $("#btnSubmit").attr("disabled", false);

    var Val = (this.checked ? "1" : "0");
    if(Val=="1"){
      $("#button").attr("disabled", false);
      return false;
    }else{
  $("#button").attr("disabled", true);
    }
  });
 
     
 }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button id="button" disabled="true" >Button</button>
<br>
<br>

<input type="checkbox" onclick="check()" /> Button Status
<input type="checkbox" onclick="check()" /> Button Status

尝试此代码, 快乐编码:-)

答案 1 :(得分:0)

      
      const checkbox = document.getElementsByTagName("input");
      const sub = document.getElementById("sub");
      sub.disabled = true;
      function check() {
        sub.disabled = true;
        for (let i = 0; i < checkbox.length; i++) {
          if (checkbox[i].type == "checkbox") {
            if (checkbox[i].checked == true) {
              sub.disabled = false;
            }
          }
        }
      }
    <form>
      <input
        type="checkbox"
        onclick="check()"
        name="firstCheck"
        value="First"
      />
      <input
        type="checkbox"
        onclick="check()"
        name="secondCheck"
        value="Second"
      />
      <input type="submit" id="sub" name="sub" />
    </form>

这是纯js。但是我建议使用jQuery。