3

Given something simple like this:

<form ...>
<input type="checkbox" required name="op1"> Option 1</u>
<input type="checkbox" required name="op2"> Option 2</u>
<input type="submit">
</form>

Is there any way using HTML5 Validation to validate if one of the boxes are checked and if none are selected to focus the required tooltip on the form?

0

2 Answers 2

2

You cannot do it just with HTML5 but here is a way to do it with javascript

Html

<form onsubmit="return checkCheckBoxes(this);">
<input type="checkbox" required name="op1"> Option 1</u>
<input type="checkbox" required name="op2"> Option 2</u>
<input type="submit">
</form>  

Javascript

 <script type="text/javascript" language="JavaScript">
    <!--
    function checkCheckBoxes(theForm) {
        if (
        theForm.opt1.checked == false &&
        theForm.opt2.checked == false) 
        {
            alert ('You didn\'t choose any of the checkboxes!');
            return false;
        } else {    
            return true;
        }
    }
    //-->
    </script> 
Sign up to request clarification or add additional context in comments.

Comments

1

You need to use JavaScript or something to archive this. This can not be done using plain HTML.

The following code worked for me. Hope it will be helpful.

<ul>
   <li><input name="check[]" type="checkbox" value="check 1" required><label>check 1</label></li>
   <li><input name="check[]" type="checkbox" value="check 2" required><label>check 2</label></li>
   <li><input name="check[]" type="checkbox" value="check 3" required><label>check 3</label></li>
   <li><input name="check[]" type="checkbox" value="check 4" required><label>check 4</label></li>
</ul>
<input type="submit" value="Check" id="check">

jQuery code,

<script type="text/javascript">
$(document).ready(function () {
    $('#check').click(function(e) {
     var ischecked = $("input[type=checkbox]:checked").length;
      if(!ischecked) {
        alert("Please select at least one checkbox.");
     return false;
      }

    });
});
</script>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.