简体   繁体   中英

using only javascript to prompt user to choose at least one checkbox

Hello I have a HTML form which already prompts users to fill empty fields. And this is the script that I am using:

<!-- Script to prompt users to fill in the empty fields -->
    <script type="text/javascript">
        document.addEventListener("DOMContentLoaded", function() {
            var elements = document.getElementsByTagName("INPUT");
            for (var i = 0; i < elements.length; i++) {
                elements[i].oninvalid = function(e) {
                    e.target.setCustomValidity("");
                    if (!e.target.validity.valid) {
                        e.target.setCustomValidity("To continue, you must correctly fill in the missing fields.");
                    }
                };
                elements[i].oninput = function(e) {
                    e.target.setCustomValidity("");
                };
            }
        });
    </script>

This script works flawlesly and it brings up a nice prompt that looks like this:

在此处输入图片说明

It works for all the input text fields, but I need another script that will (a) check if at least one checkbox you can see at the bottom of the form is checked, and (b) will bring up a prompt which is styled the same way as the one above.

I looked at other posts and wrote the below script. I referenced checkboxes by their IDs and somehow used the function function(e) from the above script. Well it won't work for me but I must be close...

<!-- Script which prompts user to check at least one checkbox -->
<script type="text/javascript">
    document.addEventListener("DOMContentLoaded", function() {
        if (
            document.getElementById("linux-c-arm-checkbox").checked == false &&
            document.getElementById("linux-eda-cad-checkbox").checked == false &&
            document.getElementById("linux-blender-checkbox").checked == false &&
            document.getElementById("linux-photo-checkbox").checked == false &&
            document.getElementById("linux-audio-checkbox").checked == false &&
            document.getElementById("linux-latex-checkbox").checked == false &&
            document.getElementById("linux-desktop-checkbox").checked == false &&
            document.getElementById("linux-office-checkbox").checked == false
        ){
            function(e) {
                e.target.setCustomValidity("");
                if (!e.target.validity.valid) {
                    e.target.setCustomValidity("Please choose at least one checkbox.");
                }
            }
        }
    });
</script> 

Can anyone help me solve this by using javascript without JQuery?

Your e is null, because you use self executing function inside if and does not pass any event for it.

Try changing e.target to document.getElementById("linux-office-checkbox") or other not-checked element.


In jQuery I would check if any checkbox is selected by doing $('.checkboxClass:checked').length > 0

Though there is no way you can put required attribute on a checkbox group and do the validation for atleast one selection, here is a workaround solution. Do the changes accordingly on your HTML.

It takes a hidden textbox as the placeholder of the selected checkbox group. If atleast one is selected the hidden field will also have the value.

 function setAccount() { if (document.querySelectorAll('input[name="gender"]:checked').length > 0) document.querySelector("#socialPlaceholder").value = document.querySelector('input[name="gender"]:checked').value; else document.querySelector("#socialPlaceholder").value = ""; } function invalidMsg(textbox) { if (textbox.value == '') { textbox.setCustomValidity('Please select at least one account'); } else { textbox.setCustomValidity(''); } } 
 <form target="_blank"> <b>Accounts</b> <input type="text" id="socialPlaceholder" required value="" style="width:0px;height:0px;position: relative;left:-30px;opacity: 0;" oninvalid="invalidMsg(this)"/><br/> <label>Facebook<input type="checkbox" name="gender" value="facebook" onClick="setAccount()"/></label> <label>Twitter<input type="checkbox" name="gender" value="twitter" onClick="setAccount()"/></label> <label>Google Plus<input type="checkbox" name="gender" value="google_plus" onClick="setAccount()"/></label> <label>Instagram<input type="checkbox" name="gender" value="instagram" onClick="setAccount()"/></label> </br> </br> <input type="submit" value="Submit" /> <br/><br/> NOTE: Submit without selecting any account to see the validation message </form> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM