Elnaz
Elnaz

Reputation: 2890

checkbox change not fired at page load time

I have a button and checkbox(terms of use) in my page.
The button should be disabled if the checkbox is not checked.

I want to reset the situation in every load. (first load or using back btn or etc) the reset state is: checkbox shouldn't be checked, and btn is disabled. But the function is called just when I click the checkbox, and not at load time. Update: Also I tested .trigger('change'), too. It did't work too

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

Upvotes: 1

Views: 321

Answers (1)

mplungjan
mplungjan

Reputation: 178094

You are calling the .change before you assign.

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

You can also put

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

at the end of your document

Upvotes: 3

Related Questions