javascript - jQuery : disable submit button if field empty or checkbox not checked

标签 javascript jquery

这是我第一次使用 jQuery,我需要你的帮助,因为我无法克服困难来制作我想要的东西。

我有一个文档表,每个文档都有一个复选框,以便选择或不选择它。

我还有一个字段,其中一个用户设置新的一年以便在之后修改文件名。

我有这个过程:

  1. 默认情况下,提交按钮处于禁用状态
  2. 要激活提交按钮,用户必须选中一个复选框写入新的一年
  3. 完成第 2 步后,如果我删除年份取消选中复选框,则必须禁用提交按钮

这是我的 javascript 部分(别忘了,这是我第一次):

<script type="application/javascript">

$(document).ready(function(){
    $('#DocumentButton').attr('disabled',true);
    $('#year').keyup(function(){
        // if field year is not empty and checkbox is checked
        if($(this).val().length !=0 && $('.fakeRadio').is(':checked'))
            $('#DocumentButton').attr('disabled', false);
        // if field year is empty or checkbox isn't checked
        else if ($(this).val().length =0 || $('.fakeRadio').is(':checked')==false)
            $('#DocumentButton').attr('disabled',true);
    })
});

   // Simulate Checkbox as Radiobox
   $(document).ready(function(){
      $(".fakeRadio").click(function(){
      var wasChecked = !$(this).prop("checked");
      $(".fakeRadio").prop( "checked", false );
      $(this).prop("checked", (!wasChecked) ? true : false );
      });
    });

  </script>

以及相应的 HTML 部分:

<div class="col-md-offset-1 col-md-5">
  <h4> {% trans "List of documents:" %} </h4>
  <form action="" method="POST"> {% csrf_token %}
    <table id="DocumentTable" class="table table-bordered table-striped table-condensed table_model"
           style="width: 160%;">
      <thead>
      <tr>
        <th style="width: 10%;">Choice</th>
        <th>Document title</th>
      </tr>
      </thead>
      <tbody>
      {% for document in query_document %}
        <tr>
          <td><input type="checkbox" class="fakeRadio" id="DocumentCheckBox" name="DocumentChoice" value="{{ document.id }}"></td>
          <td>{{ document.title }}</td>
        </tr>
      {% endfor %}
      </tbody>
    </table>

    <input type="text" id="year" name="q1year" placeholder="Set new year" value="{{ request.get.q1year }}">
    <button class="btn btn-default" id="DocumentButton" type="submit" name="UpdateDocument">{% trans "Submit" %}</button>
  </form>
</div>

到目前为止,该过程在步骤 1 和 2 中运行良好,但如果我取消选中该复选框,则无法正常运行。

你能帮我解释一下我的代码中有什么错误吗?

最佳答案

HTML5 验证可以为您做到这一点。不需要 JavaScript。只需将 required 属性添加到元素即可。

<form>
  <label>

  <label for="name">name</label><input id="name" required />
  <br/>
  <input type="checkbox" required name="terms"> I accept the Terms and Conditions
  </label>
  <br/>

  <input type="submit">
</form>

但是,如果您想使用 JavaScript 来完成此操作,则可以创建一种方法来执行这两项检查。用一种方法进行所有检查比尝试弄清楚如何对每个输入进行单独检查要容易得多。

function checkValid () {
  var cbChecked = $("#cb").is(":checked");  // check if checked
  var hasText = $("#name").val().length > 0;  // check if it has text
  
  $("#btnSubmit").prop("disabled", !cbChecked || !hasText);
}

$( function () {
  checkValid(); // run it for the first time
  $("#cb").on("change", checkValid);  // bind checkbox
  $("#name").on("input", checkValid)  // bind textbox
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
  <label>

  <label for="name">name</label><input id="name" />
  <br/>
  <input id="cb" type="checkbox" name="terms"> I accept the Terms and Conditions
  </label>
  <br/>

  <input type="submit" id="btnSubmit">
</form>

如果您有多个复选框,但只需要一个,则需要使用 JavaScript

function checkValid () {
  var cbChecked = $(".cb:checked").length > 0;  // check if at least one checked
  var hasText = $("#name").val().length > 0;  // check if it has text
  
  $("#btnSubmit").prop("disabled", !cbChecked || !hasText);
}

$( function () {
  checkValid(); // run it for the first time
  $(".cb").on("change", checkValid);  // bind checkboxesvia classname
  $("#name").on("input", checkValid)  // bind textbox
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
  <label>

  <label for="name">name</label><input id="name" />
  <br/>
  <label>
  <input class="cb" type="checkbox" name="terms"> One
  </label>
  <label>
  <input class="cb" type="checkbox" name="terms"> Two
  </label>
  <label>
  <input class="cb" type="checkbox" name="terms"> Three
  </label>
  <br/>

  <input type="submit" id="btnSubmit">
</form>

关于javascript - jQuery : disable submit button if field empty or checkbox not checked,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51968578/

相关文章:

javascript - React Native Expo 未捕获错误 'this.props=t'

javascript - Rails 3 - 如何动态创建与参数关联的 html 元素 [ :id]?

javascript - 使用 window.location.href 防止 'Confirm Navigation' 警报

java - 如何使用从 Spring MVC 发回的 JSON 对象填充 jQuery 数据表的行?

jquery - 保持背景图像居中

javascript - 是否可以在访问时创建或交换 Javascript 属性

javascript - Angular 1.5 的单向数据绑定(bind)像双向一样工作

javascript - 在我的 javascript 中永远不会触发成功事件以进行轮询事件

javascript - JQuery 101 - 更改文本值

jquery - 将网格项动画到新位置