Search code examples
htmlformshtml-tag-details

How to show form required warning in collapsed details?


I have a form with a required checkbox inside a details tag. When the user tries to submit the site without checking the checkbox a warning is displayed.

But when the user has collapsed the details no warning is shown and the submit just doesn't work. Is there a clean html way to get this working or do I need to use javascript? I am basically expecting the browser to automatically open the details and show the warning at the checkbox.

See this demo for the problem https://jsfiddle.net/1jwdm8ov/

<html>
    <form>
        <details>
            <input type="checkbox" required="required">
        </details>
        <input type="submit">
    </form>
</html>

Solution

  • I can't think of a way to do this with CSS, but you can use javascript to hook in to the browsers form validation and check if a field is required. If an input is required and has not been completed, you can open the parent details element using .open = true;, which will allow the required message to be visible.

    var detailInputs = document.querySelectorAll('form details input');
    
    [].forEach.call(detailInputs, function(detailInputs) {
      detailInputs.addEventListener('invalid',function(e){
        detailInputs.parentNode.open = true;
      });
    });
    <form>
      <details>
        <input type="checkbox" required="required">
      </details>
      <input type="submit">
    </form>