Delay HTML5 :invalid pseudo-class until the first event

前端 未结 13 2031
旧巷少年郎
旧巷少年郎 2020-11-30 04:35

I recently discovered that the :invalid pseudo-class applies to required form elements as soon as the page loads. For example, if you have this cod

相关标签:
13条回答
  • 2020-11-30 05:12

    There is a html5 invalid event that fires on form elements before the submit event occurs for each element that does not pass checkValidity. You can use this event to apply a class for example to the surrounding form and display :invalid styles only after this event occurs.

     $("form input, form select, form textarea").on("invalid", function() {
         $(this).closest('form').addClass('invalid');
     });
    

    Your CSS would then look something like this:

    :invalid { box-shadow: none; }
    .invalid input:invalid,
    .invalid textarea:invalid,
    .invalid select:invalid { border: 1px solid #A90909 !important; background-color: #EEC2C2; }
    

    The first line removes the default styling, so form elements look neutral at page load. As soon as the invalid event fires (when a user tries to submit the form), the elements are visibly rendered invalid.

    0 讨论(0)
提交回复
热议问题