2

My goal is..
When the checkbox is selected, button is enabled.
When the checkbox is not selected, button is disabled.

Defaults : checkbox is disabled

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>

<button type="button" id="agree" class="btn btn-primary">Let's Go!</button>
<label><input type="checkbox" id="checkbox" disabled value="">I agree.</label>

<script>
$(document).ready(function(){
    if($('input:checkbox[id="checkbox"]').is(':checked') == true) {
        $("#agree").attr("disabled",false);
    }
    else {
      $("#agree").attr("disabled",true);
    }
});
</script>
F. Kim
  • 53
  • 1
  • 9

3 Answers3

2

First of all you are disabling input. Second - you are not listening for input change event.

$(document).ready(function() {
  $('#checkbox').change(function() {
    $("#agree").prop("disabled", !$(this).is(':checked'));
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>

<button type="button" id="agree" disabled="disabled" class="btn btn-primary">Let's Go!</button>
<label>
  <input type="checkbox" id="checkbox" value="">I agree.</label>

Notes

Changing attribute value does not changes attribute property. Check here
Do not overkill selector. input:checkbox[id="checkbox"] is slower than simple #checkbox
Always try to optimize and minify your code.

Community
  • 1
  • 1
Justinas
  • 41,402
  • 5
  • 66
  • 96
0

Try using like this,

$(document).ready(function(){
    if($('input#checkbox').prop('checked') == true) {
        $("#agree").prop("disabled",false);
    }
    else {
      $("#agree").prop("disabled",true);
    }
});

Or

$(document).ready(function(){
    if($('input#checkbox').prop('checked') == 'checked') {
        $("#agree").prop("disabled",false);
    }
    else {
      $("#agree").prop("disabled",true);
    }
});
Samir
  • 1,312
  • 1
  • 10
  • 16
0

$(document).ready(function() {
  $('input:checkbox#checkbox').change(function() {
    console.log($(this).is(':checked'))
    $("#agree").prop("disabled", !$(this).is(':checked'));
  }).change();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>

<button type="button" id="agree" class="btn btn-primary">Let's Go!</button>
<label>
  <input type="checkbox" id="checkbox" value="">I agree.</label>

Use like this for single line

guradio
  • 15,524
  • 4
  • 36
  • 57
  • `$("#agree").prop("disabled", !$(this).is(':checked'));` this is what i am referring mate no need for if condition – guradio Oct 28 '16 at 08:48