Disable and enable button with checkbox checked

649 views javascript
6

I have a button on my form which is disabled by default

<input disabled type="submit" value="" name="subscribe" id="mc-embedded-subscribe" class="subscribe__button">

I also have a optin checkbox:

 <label class="subscribe__optin">
     <input id="optin" type="checkbox" value="true" name="optin"> Ja, ik ga akkoord met de privacyverklaring
 </label>

The idea is, if the checkbox is selected, the button must be clickable. But if you unselect the checkbox again after it's selected, the button must be disabled.

My jQuery code is:

$("#optin").on("change", function(e){
        if($("#optin").attr("checked")){
            $("#mc-embedded-subscribe").attr('disabled','disabled');
            console.log('checked');
        } else {
            $("#mc-embedded-subscribe").removeAttr('disabled');
            console.log('not checked');
        }
});

When I click on the checkbox, I always get 'not checked' in my console. What am I doing wrong over here? I already checked some other example here on stackoverflow, but none of these seem the help my problem.

answered question

Check the syntax for .attr() you are failing to check what you would like to

3 Answers

7

Already found a solution. It seems that .attr() was the issue. I have to use .prop()

$("#optin").on("change", function(e){
        if($("#optin").prop("checked")){
            $("#mc-embedded-subscribe").removeAttr('disabled');
            console.log('enabled');
        } else {
            $("#mc-embedded-subscribe").attr('disabled','disabled');
            console.log('disabled');

        }
});

posted this
13

Instead of using

    if($("#optin").attr("checked")){

try:

    if($(this)[0].checked){

posted this
9

What you want is to raise an event onClick and not onChange. Try something like this post: How to check whether a checkbox is checked in jQuery?

posted this

Have an answer?

JD

Please login first before posting an answer.