【问题标题】:checkbox change not fired at page load time页面加载时未触发复选框更改
【发布时间】:2017-02-21 17:00:26
【问题描述】:

我的页面中有一个按钮和复选框(使用条款)。
如果未选中复选框,则应禁用该按钮。

我想在每次加载时重置情况。 (第一次加载或使用返回 btn 等)重置状态是:不应该选中复选框,并且 btn 被禁用。 但是该函数仅在我单击复选框时调用,而不是在加载时调用。 更新:我也测试了.trigger('change')。它也没有工作

$(function() {
  $('#termsOfUse').removeAttr('checked');
  $('#termsOfUse').change();
  $('#termsOfUse').change(function() {
    if ($(this).is(":checked")) {
      $('#createBtn').prop('disabled', false);
    } else {
      $('#createBtn').prop('disabled', true);
    }
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="row">
  <input id="termsOfUse" type="checkbox" />
  <label for="termsOfUse" style="display: inline;">
                   <span><a href="/rules">rules</a></span> I am agree with</label>
</div>
<div class="create">
  <input id="createBtn" type="button" value="create" class="btn btn-default btn-success" 
  onclick="location.href = '@Url.Action("Create","NewOne ")'" />
</div>

【问题讨论】:

  • 使用$(document).ready(function () {YOUR CODE})
  • 移动 $('#termsOfUse').change();到事件处理程序分配之后
  • @amirhoseinahmadi OP 已经在这样做了

标签: javascript jquery checkbox


【解决方案1】:

您在分配之前调用了 .change。

$(function() {
  $('#termsOfUse').prop('checked',false);
  $('#termsOfUse').change(function() {
    $('#createBtn').prop('disabled', !this.checked);
  }).change(); // execute at load
});

你也可以放

<script>
  $('#termsOfUse').prop('checked',false);
  $('#termsOfUse').change(function() {
    $('#createBtn').prop('disabled', !this.checked);
  }).change(); // execute at load
 </script>
 </body>

在文档的末尾

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-06-18
    • 2018-02-11
    • 1970-01-01
    • 2018-06-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多