Fabrizio Cocco
Fabrizio Cocco

Reputation: 171

Click Checkbox to disabled button

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/>

Upvotes: 0

Views: 96

Answers (2)

iCollect.it Ltd
iCollect.it Ltd

Reputation: 93561

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'));
    });
});

Upvotes: 3

Roko C. Buljan
Roko C. Buljan

Reputation: 206048

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.

Upvotes: 3

Related Questions