Add/remove class based on checkboxes











up vote
1
down vote

favorite












I have a small form that is kind of working. There are 2 options, A and B.



If A and B are NO then disable the button. If A OR B are YES then remove the disable class from the button. That's what I'm aiming for, this is what I have:



$('.check-opt').change(function () {
if ($('input[name="step_2"],[name="step_4"]:checked').val() == "yes") {
$('#order_btn_id').removeClass('disabled');
} else {
$('#order_btn_id').addClass('disabled');
}
});


It's kind of working in the sense that it removes the disabled class when choosing A OR B, but when you select both A and B as NO then the disabled class isn't added back in. Where have I gone wrong?



Many thanks!










share|improve this question
























  • You can use toggleClass instead of add/remove class.
    – Shubham Baranwal
    Nov 22 at 11:28















up vote
1
down vote

favorite












I have a small form that is kind of working. There are 2 options, A and B.



If A and B are NO then disable the button. If A OR B are YES then remove the disable class from the button. That's what I'm aiming for, this is what I have:



$('.check-opt').change(function () {
if ($('input[name="step_2"],[name="step_4"]:checked').val() == "yes") {
$('#order_btn_id').removeClass('disabled');
} else {
$('#order_btn_id').addClass('disabled');
}
});


It's kind of working in the sense that it removes the disabled class when choosing A OR B, but when you select both A and B as NO then the disabled class isn't added back in. Where have I gone wrong?



Many thanks!










share|improve this question
























  • You can use toggleClass instead of add/remove class.
    – Shubham Baranwal
    Nov 22 at 11:28













up vote
1
down vote

favorite









up vote
1
down vote

favorite











I have a small form that is kind of working. There are 2 options, A and B.



If A and B are NO then disable the button. If A OR B are YES then remove the disable class from the button. That's what I'm aiming for, this is what I have:



$('.check-opt').change(function () {
if ($('input[name="step_2"],[name="step_4"]:checked').val() == "yes") {
$('#order_btn_id').removeClass('disabled');
} else {
$('#order_btn_id').addClass('disabled');
}
});


It's kind of working in the sense that it removes the disabled class when choosing A OR B, but when you select both A and B as NO then the disabled class isn't added back in. Where have I gone wrong?



Many thanks!










share|improve this question















I have a small form that is kind of working. There are 2 options, A and B.



If A and B are NO then disable the button. If A OR B are YES then remove the disable class from the button. That's what I'm aiming for, this is what I have:



$('.check-opt').change(function () {
if ($('input[name="step_2"],[name="step_4"]:checked').val() == "yes") {
$('#order_btn_id').removeClass('disabled');
} else {
$('#order_btn_id').addClass('disabled');
}
});


It's kind of working in the sense that it removes the disabled class when choosing A OR B, but when you select both A and B as NO then the disabled class isn't added back in. Where have I gone wrong?



Many thanks!







jquery






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Nov 22 at 14:23









Rory McCrossan

240k29203244




240k29203244










asked Nov 22 at 11:26









Edward Hill

297




297












  • You can use toggleClass instead of add/remove class.
    – Shubham Baranwal
    Nov 22 at 11:28


















  • You can use toggleClass instead of add/remove class.
    – Shubham Baranwal
    Nov 22 at 11:28
















You can use toggleClass instead of add/remove class.
– Shubham Baranwal
Nov 22 at 11:28




You can use toggleClass instead of add/remove class.
– Shubham Baranwal
Nov 22 at 11:28












2 Answers
2






active

oldest

votes

















up vote
5
down vote



accepted










The issue with your logic is that you're calling val() on a collection of elements, so it will only read the value of the first one.



The easiest way to achieve what you need is to use toggleClass() along with a boolean to determine if the class should be added or removed. You can set the state of that boolean depending on whether or not both checkboxes are unchecked, like this:






$('.check-opt').change(function() {
var disabled = !$('input[name="step_2"]').prop('checked') && !$('input[name="step_4"]').prop('checked');
$('#order_btn_id').toggleClass('disabled', disabled);
});

.disabled {
background-color: #CCC;
color: #666;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="checkbox" name="step_2" class="check-opt" />
<input type="checkbox" name="step_4" class="check-opt" />
<button id="order_btn_id" class="disabled">Order</button>





This could potentially be simplified to check if any .check-opt element is checked, but this depends on how many groups of checkboxes you have in the DOM:



var disabled = $('.check-opt:checked').length == 0;


Also note that if you want to completely disable the button it would be worth setting prop('disabled', true) as well as adding the class to it.






share|improve this answer























  • Wondeful, that sorted it! Thankyou so much, ill mark it as the answer in 8mins..
    – Edward Hill
    Nov 22 at 11:33


















up vote
0
down vote













Use two selectors for your query:



var a = $('input[name="step_2"]:checked').val() == "yes";
var b = $('[name="step_4"]:checked').val() == "yes";

$('#order_btn_id').toggleClass('disabled', a || b)





share|improve this answer





















    Your Answer






    StackExchange.ifUsing("editor", function () {
    StackExchange.using("externalEditor", function () {
    StackExchange.using("snippets", function () {
    StackExchange.snippets.init();
    });
    });
    }, "code-snippets");

    StackExchange.ready(function() {
    var channelOptions = {
    tags: "".split(" "),
    id: "1"
    };
    initTagRenderer("".split(" "), "".split(" "), channelOptions);

    StackExchange.using("externalEditor", function() {
    // Have to fire editor after snippets, if snippets enabled
    if (StackExchange.settings.snippets.snippetsEnabled) {
    StackExchange.using("snippets", function() {
    createEditor();
    });
    }
    else {
    createEditor();
    }
    });

    function createEditor() {
    StackExchange.prepareEditor({
    heartbeatType: 'answer',
    convertImagesToLinks: true,
    noModals: true,
    showLowRepImageUploadWarning: true,
    reputationToPostImages: 10,
    bindNavPrevention: true,
    postfix: "",
    imageUploader: {
    brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
    contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
    allowUrls: true
    },
    onDemand: true,
    discardSelector: ".discard-answer"
    ,immediatelyShowMarkdownHelp:true
    });


    }
    });














    draft saved

    draft discarded


















    StackExchange.ready(
    function () {
    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53429935%2fadd-remove-class-based-on-checkboxes%23new-answer', 'question_page');
    }
    );

    Post as a guest















    Required, but never shown

























    2 Answers
    2






    active

    oldest

    votes








    2 Answers
    2






    active

    oldest

    votes









    active

    oldest

    votes






    active

    oldest

    votes








    up vote
    5
    down vote



    accepted










    The issue with your logic is that you're calling val() on a collection of elements, so it will only read the value of the first one.



    The easiest way to achieve what you need is to use toggleClass() along with a boolean to determine if the class should be added or removed. You can set the state of that boolean depending on whether or not both checkboxes are unchecked, like this:






    $('.check-opt').change(function() {
    var disabled = !$('input[name="step_2"]').prop('checked') && !$('input[name="step_4"]').prop('checked');
    $('#order_btn_id').toggleClass('disabled', disabled);
    });

    .disabled {
    background-color: #CCC;
    color: #666;
    }

    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <input type="checkbox" name="step_2" class="check-opt" />
    <input type="checkbox" name="step_4" class="check-opt" />
    <button id="order_btn_id" class="disabled">Order</button>





    This could potentially be simplified to check if any .check-opt element is checked, but this depends on how many groups of checkboxes you have in the DOM:



    var disabled = $('.check-opt:checked').length == 0;


    Also note that if you want to completely disable the button it would be worth setting prop('disabled', true) as well as adding the class to it.






    share|improve this answer























    • Wondeful, that sorted it! Thankyou so much, ill mark it as the answer in 8mins..
      – Edward Hill
      Nov 22 at 11:33















    up vote
    5
    down vote



    accepted










    The issue with your logic is that you're calling val() on a collection of elements, so it will only read the value of the first one.



    The easiest way to achieve what you need is to use toggleClass() along with a boolean to determine if the class should be added or removed. You can set the state of that boolean depending on whether or not both checkboxes are unchecked, like this:






    $('.check-opt').change(function() {
    var disabled = !$('input[name="step_2"]').prop('checked') && !$('input[name="step_4"]').prop('checked');
    $('#order_btn_id').toggleClass('disabled', disabled);
    });

    .disabled {
    background-color: #CCC;
    color: #666;
    }

    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <input type="checkbox" name="step_2" class="check-opt" />
    <input type="checkbox" name="step_4" class="check-opt" />
    <button id="order_btn_id" class="disabled">Order</button>





    This could potentially be simplified to check if any .check-opt element is checked, but this depends on how many groups of checkboxes you have in the DOM:



    var disabled = $('.check-opt:checked').length == 0;


    Also note that if you want to completely disable the button it would be worth setting prop('disabled', true) as well as adding the class to it.






    share|improve this answer























    • Wondeful, that sorted it! Thankyou so much, ill mark it as the answer in 8mins..
      – Edward Hill
      Nov 22 at 11:33













    up vote
    5
    down vote



    accepted







    up vote
    5
    down vote



    accepted






    The issue with your logic is that you're calling val() on a collection of elements, so it will only read the value of the first one.



    The easiest way to achieve what you need is to use toggleClass() along with a boolean to determine if the class should be added or removed. You can set the state of that boolean depending on whether or not both checkboxes are unchecked, like this:






    $('.check-opt').change(function() {
    var disabled = !$('input[name="step_2"]').prop('checked') && !$('input[name="step_4"]').prop('checked');
    $('#order_btn_id').toggleClass('disabled', disabled);
    });

    .disabled {
    background-color: #CCC;
    color: #666;
    }

    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <input type="checkbox" name="step_2" class="check-opt" />
    <input type="checkbox" name="step_4" class="check-opt" />
    <button id="order_btn_id" class="disabled">Order</button>





    This could potentially be simplified to check if any .check-opt element is checked, but this depends on how many groups of checkboxes you have in the DOM:



    var disabled = $('.check-opt:checked').length == 0;


    Also note that if you want to completely disable the button it would be worth setting prop('disabled', true) as well as adding the class to it.






    share|improve this answer














    The issue with your logic is that you're calling val() on a collection of elements, so it will only read the value of the first one.



    The easiest way to achieve what you need is to use toggleClass() along with a boolean to determine if the class should be added or removed. You can set the state of that boolean depending on whether or not both checkboxes are unchecked, like this:






    $('.check-opt').change(function() {
    var disabled = !$('input[name="step_2"]').prop('checked') && !$('input[name="step_4"]').prop('checked');
    $('#order_btn_id').toggleClass('disabled', disabled);
    });

    .disabled {
    background-color: #CCC;
    color: #666;
    }

    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <input type="checkbox" name="step_2" class="check-opt" />
    <input type="checkbox" name="step_4" class="check-opt" />
    <button id="order_btn_id" class="disabled">Order</button>





    This could potentially be simplified to check if any .check-opt element is checked, but this depends on how many groups of checkboxes you have in the DOM:



    var disabled = $('.check-opt:checked').length == 0;


    Also note that if you want to completely disable the button it would be worth setting prop('disabled', true) as well as adding the class to it.






    $('.check-opt').change(function() {
    var disabled = !$('input[name="step_2"]').prop('checked') && !$('input[name="step_4"]').prop('checked');
    $('#order_btn_id').toggleClass('disabled', disabled);
    });

    .disabled {
    background-color: #CCC;
    color: #666;
    }

    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <input type="checkbox" name="step_2" class="check-opt" />
    <input type="checkbox" name="step_4" class="check-opt" />
    <button id="order_btn_id" class="disabled">Order</button>





    $('.check-opt').change(function() {
    var disabled = !$('input[name="step_2"]').prop('checked') && !$('input[name="step_4"]').prop('checked');
    $('#order_btn_id').toggleClass('disabled', disabled);
    });

    .disabled {
    background-color: #CCC;
    color: #666;
    }

    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <input type="checkbox" name="step_2" class="check-opt" />
    <input type="checkbox" name="step_4" class="check-opt" />
    <button id="order_btn_id" class="disabled">Order</button>






    share|improve this answer














    share|improve this answer



    share|improve this answer








    edited Nov 22 at 11:35

























    answered Nov 22 at 11:30









    Rory McCrossan

    240k29203244




    240k29203244












    • Wondeful, that sorted it! Thankyou so much, ill mark it as the answer in 8mins..
      – Edward Hill
      Nov 22 at 11:33


















    • Wondeful, that sorted it! Thankyou so much, ill mark it as the answer in 8mins..
      – Edward Hill
      Nov 22 at 11:33
















    Wondeful, that sorted it! Thankyou so much, ill mark it as the answer in 8mins..
    – Edward Hill
    Nov 22 at 11:33




    Wondeful, that sorted it! Thankyou so much, ill mark it as the answer in 8mins..
    – Edward Hill
    Nov 22 at 11:33












    up vote
    0
    down vote













    Use two selectors for your query:



    var a = $('input[name="step_2"]:checked').val() == "yes";
    var b = $('[name="step_4"]:checked').val() == "yes";

    $('#order_btn_id').toggleClass('disabled', a || b)





    share|improve this answer

























      up vote
      0
      down vote













      Use two selectors for your query:



      var a = $('input[name="step_2"]:checked').val() == "yes";
      var b = $('[name="step_4"]:checked').val() == "yes";

      $('#order_btn_id').toggleClass('disabled', a || b)





      share|improve this answer























        up vote
        0
        down vote










        up vote
        0
        down vote









        Use two selectors for your query:



        var a = $('input[name="step_2"]:checked').val() == "yes";
        var b = $('[name="step_4"]:checked').val() == "yes";

        $('#order_btn_id').toggleClass('disabled', a || b)





        share|improve this answer












        Use two selectors for your query:



        var a = $('input[name="step_2"]:checked').val() == "yes";
        var b = $('[name="step_4"]:checked').val() == "yes";

        $('#order_btn_id').toggleClass('disabled', a || b)






        share|improve this answer












        share|improve this answer



        share|improve this answer










        answered Nov 22 at 11:30









        Justinas

        26.9k33457




        26.9k33457






























            draft saved

            draft discarded




















































            Thanks for contributing an answer to Stack Overflow!


            • Please be sure to answer the question. Provide details and share your research!

            But avoid



            • Asking for help, clarification, or responding to other answers.

            • Making statements based on opinion; back them up with references or personal experience.


            To learn more, see our tips on writing great answers.





            Some of your past answers have not been well-received, and you're in danger of being blocked from answering.


            Please pay close attention to the following guidance:


            • Please be sure to answer the question. Provide details and share your research!

            But avoid



            • Asking for help, clarification, or responding to other answers.

            • Making statements based on opinion; back them up with references or personal experience.


            To learn more, see our tips on writing great answers.




            draft saved


            draft discarded














            StackExchange.ready(
            function () {
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53429935%2fadd-remove-class-based-on-checkboxes%23new-answer', 'question_page');
            }
            );

            Post as a guest















            Required, but never shown





















































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown

































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown







            Popular posts from this blog

            Contact image not getting when fetch all contact list from iPhone by CNContact

            count number of partitions of a set with n elements into k subsets

            A CLEAN and SIMPLE way to add appendices to Table of Contents and bookmarks