0

I want to disabled the button to send the form until the checkbox is set and i want to solve it with a nice short jQuery Code. But there has to be a bug, nothing happens. Does anyone have an idea?

JS:

$(document).ready(function(){
$('#terms').keyup(function(){
    if($('#terms').is(':checked')){
          $('#btn').removeAttr('disabled');
    }else{
        $('#btn').attr('disabled');
}})}

HTML:

<input id="terms" type="checkbox" value="" name="terms">
    <input id="btn"   name="register" type="button" value="Register" disabled/>
  • possible duplicate of [How do i disable a submit button when checkbox is uncheck?](http://stackoverflow.com/questions/5458531/how-do-i-disable-a-submit-button-when-checkbox-is-uncheck) – Liam Jul 29 '15 at 14:15
  • Use the [`prop`](http://api.jquery.com/prop/) method _correctly_ instead of the `attr`. http://stackoverflow.com/questions/5874652/prop-vs-attr – Ram Jul 29 '15 at 14:21

2 Answers2

3

Actually it's really simple:

$('#terms').on("change", function() {
  $("#btn").prop("disabled", !this.checked);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="terms" type="checkbox" value="" name="terms">
<input id="btn"   name="register" type="button" value="Register" disabled/>

where the !this.checked is the boolean value of the current checkbox state.
Naturally there's a jQuery way: $(this).is(":not(:checked)") but there's no need to, since you should get used to understand the this environment and the DOM Properties you have available using simple vanilla JS read more.

Community
  • 1
  • 1
Roko C. Buljan
  • 196,159
  • 39
  • 305
  • 313
3

Use prop() instead of attr:

e.g.

$('#btn').prop('disabled', true);

Properties generally affect the dynamic state of a DOM element without changing the serialized HTML attribute. Examples include the value property of input elements, the disabled property of inputs and buttons, or the checked property of a checkbox. The .prop() method should be used to set disabled and checked instead of the .attr() method. The .val() method should be used for getting and setting value.

Note: You are using keyup instead of the change event for a checkbox.

Note your example can be simplified to just pass a boolean expression for on/off:

$(function(){
    $('#terms').change(function(){
        $('#btn').prop('disabled', !$(this).is(':checked'));
    });
});
iCollect.it Ltd
  • 92,391
  • 25
  • 181
  • 202