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

Time:02-06

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)

<div >
 a : <input type="checkbox" name="a"  required><br>
 b : <input type="checkbox" name="b"  required><br>
 c : <input type="checkbox" name="c"  required><br>
 d : <input type="checkbox" name="d"  required><br>
 e : <input type="checkbox" name="e"  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.

CodePudding user response:

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()
});
  • Related