1

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.

Dennis
  • 528
  • 3
  • 24
  • Check the syntax for .attr() you are failing to check what you would like to – Lelio Faieta Nov 06 '18 at 14:52
  • 1
    Possible duplicate of [How to check whether a checkbox is checked in jQuery?](https://stackoverflow.com/questions/901712/how-to-check-whether-a-checkbox-is-checked-in-jquery) – lumio Nov 06 '18 at 14:52

3 Answers3

1

http://api.jquery.com/prop/

It's the difference between attributes and properties, just that while developing, we hardly regard the difference and treat both as same.

NitinSingh
  • 2,029
  • 1
  • 15
  • 33
0

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

        }
});
Dennis
  • 528
  • 3
  • 24
0

Instead of using

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

try:

    if($(this)[0].checked){
qocu
  • 385
  • 4
  • 13