Delay HTML5 :invalid pseudo-class until the first event

前端 未结 13 2080
旧巷少年郎
旧巷少年郎 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 04:50

    Following on from agouseh's idea, you can have a bit of javascript to tell when the submit button has been focussed, and have validation show up at that time.

    The javascript will add a class (eg. submit-focussed) to the form field when the submit button is focussed or clicked, which then allows the CSS to style invalid inputs.

    This follows the best practice of showing validation feedback after the user has finished filling in the fields, as according to research there is no additional benefit to showing it during the process.

    document
      .querySelector('input[type=submit]')
      .onfocus = function() {
        this
          .closest('form')
          .classList
          .add('submit-focussed');
      };
    form.submit-focussed input:invalid {
      border: thin solid red;
    }

    jQuery alternative

    (function($) {
      $('input[type=submit]').on('focus', function() {
        $(this)
          .parent('form')
          .addClass('submit-focussed');
      });
    })(jQuery); /* WordPress compatible */
    

提交回复
热议问题