Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

If any of them is already selected, the script does not detect

I have a checkbox-required script that normally works.
But the problem I can’t solve is: If any of them is already selected, the script does not detect the selected one and says choose. It works when you click at least once. What should I do, I would appreciate it if you could help, thank you.

DEMO (Normally is working)

MY DEMO (Any already selected)

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

<div class="options111">
 a : <input type="checkbox" name="a" class="check" required><br>
 b : <input type="checkbox" name="b" class="check" required><br>
 c : <input type="checkbox" name="c" class="check" required><br>
 d : <input type="checkbox" name="d" class="check" required><br>
 e : <input type="checkbox" name="e" class="check" required checked><br>   
     </div>



$(function(){ // checkbox REQUIRED
    var requiredCheckboxes = $('.options111 :checkbox[required]');
    requiredCheckboxes.change(function(){
        if(requiredCheckboxes.is(':checked')) {
            requiredCheckboxes.removeAttr('required');
        } else {
            requiredCheckboxes.attr('required', 'required');
        }
    });
});

I tried to make changes with similar examples but I failed.
There are different examples but this script is ideal for me since I am sending the form with Ajax Load.

>Solution :

This is because you are attaching the function to remove the required attribute to the change method.

What you could do is to run the inner function once before doing anything, and also attaching the function to the change handler

$(function(){
    var requiredCheckboxes = $('.options :checkbox[required]');
    var changeFunction = function(){
        if(requiredCheckboxes.is(':checked')) {
            requiredCheckboxes.removeAttr('required');
        } else {
            requiredCheckboxes.attr('required', 'required');
        }
    }
    requiredCheckboxes.change(changeFunction);
    changeFunction()
});
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading