chuckd
chuckd

Reputation: 14610

Checkbox button disabled not working in JQuery

I'm trying to enable and disable a button when a checkbox gets checked, but can't seem to get it working. The button doesn't enable when I check the checkbox.

$("input[type=checkbox]").on("click", function() {
  var id = $(this).data("studentcheckboxid");
  var button = $("div").find("[data-studentbuttonid='" + id + "']");
  $(button).prop('disabled', false);
});
<div class="row registerColumns">
  <div class="col-md-6 col-sm-6" style="border: 1px solid brown;">
    <div id="acceptBox" style="padding: 5px; margin: 5px; border: 1px solid black;">
      Accept
      <input type="checkbox" class="studentCheckbox" [email protected]>
    </div>
  </div>
  <div class="col-md-6 col-sm-6" style="border: 1px solid red;">
    <div class="btn btn-primary disabled registerStudent" [email protected] style="padding: 5px; margin: 5px; border: 1px solid black;">
      Register Student
    </div>
  </div>
</div>

Upvotes: 1

Views: 332

Answers (3)

hammus
hammus

Reputation: 2612

   $("input[type=checkbox]").on("change", function() {
  var id = $(this).attr('data-studentcheckboxid');
  var button = $("button[data-studentbuttonid='" + id + "']")
  .prop('disabled', function(i, v) { return !v; });
});
<div class="row registerColumns">
  <div class="col-md-6 col-sm-6" style="border: 1px solid brown;">
<div id="acceptBox" style="padding: 5px; margin: 5px; border: 1px solid black;">
  Accept
  <input type="checkbox" class="studentCheckbox" data-studentcheckboxid="SomeId">
</div>
  </div>
  <div class="col-md-6 col-sm-6" style="border: 1px solid red;">
<div class="btn btn-primary disabled registerStudent" data-studentbuttonid="SomeId" style="padding: 5px; margin: 5px; border: 1px solid black;">
  Register Student
</div>
  </div>
</div>

<button data-studentbuttonid="SomeId" style="height: 20px; width: 50px;" disabled>Button</button>

Working Fiddle

Upvotes: 0

guradio
guradio

Reputation: 15565

$("input[type=checkbox]").on("click", function () {
    var id = $(this).data("studentcheckboxid");
    var button = $("div").find("[data-studentbuttonid='" + id + "']");

    if ($(this).is(':checked')) {
        $(button).prop('disabled', true);
    } else {
        $(button).prop('disabled', false);
    }
});

Although i cant find any button i made a fiddle and made a button myself you can check it here

Upvotes: 1

polent
polent

Reputation: 21

Use on change. Click is fired before state change.

Upvotes: 2

Related Questions