0

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>
Toto
  • 89,455
  • 62
  • 89
  • 125
hoanns
  • 23
  • 5

1 Answers1

1

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>
WizardCoder
  • 3,353
  • 9
  • 20
  • Thanks, I used jQuery: ```$('form details input').on('invalid', function () { $(this).closest('details').prop('open', true); });``` – hoanns Jun 18 '19 at 14:26
  • That works too. The solution above is pure Javascript, so if you are ever concerned about performance in the future, you can use that. – WizardCoder Jun 18 '19 at 14:30