简体   繁体   中英

How do I manually invoke browser highlight of not filled in input fields?

I have a form that is expanded dynamically based on user input. First, the user gets a basic form with some key questions, and then based on how the user answered these questions a bunch of additional questions are loaded using AJAX. The AJAX loading is invoked with a button labeled "next".

Before the "next" button can send a request to the server, all questions must be filled in. I can easily do this with some javascript code that fires up an alert message telling the user some of the questions are unanswered, but I would really like to get the same user experience as trying to submit a form with not-filled-in inputs that are marked "required", where the browser highlights the problematic fields.

How can this be done?

Try using reportValidity()

<html>
<form>
    <input type="text" required>
    <button type="button">Validate</button>
</form>
<script>
    document.querySelector('button').onclick = function(){
        document.querySelector('form').reportValidity();
    }
</script>
</html>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM