Validation in HTML5. :invalid classe after submit

前端 未结 9 2456
清歌不尽
清歌不尽 2021-02-18 14:11

I\'m building a form and I want to use the :invalid selector to give the \"required\" input fields a red border if the user presses submit without filling them, but

9条回答
  •  孤街浪徒
    2021-02-18 14:33

    I used this approach for a project of mine, so the invalid fields would be highlighted only after submit:

    HTML:

    CSS:

    input.required:invalid {
        color: red;
    }
    

    JS (jQuery):

    $('[type="submit"]').on('click', function () {
        // this adds 'required' class to all the required inputs under the same 
    as the submit button $(this) .closest('form') .find('[required]') .addClass('required'); });

提交回复
热议问题