F. Kim F. Kim - 1 month ago 18
jQuery Question

jQuery checkbox selected judgment

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>




Answer

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.