简体   繁体   English

如何手动调用未填写输入字段的浏览器突出显示?

[英]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. 首先,用户获得带有一些关键问题的基本表格,然后根据用户如何回答这些问题,使用AJAX加载大量其他问题。 The AJAX loading is invoked with a button labeled "next". AJAX加载通过标记为“下一步”的按钮来调用。

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. 在“下一步”按钮可以向服务器发送请求之前,必须先填写所有问题。我可以使用一些javascript代码轻松地完成此操作,这些javascript代码会发出警报消息,告诉用户某些问题未得到答复,但是我会真的希望获得与尝试提交带有未填写的输入(标记为“必填”)的表单相同的用户体验,浏览器会在其中突出显示有问题的字段。

How can this be done? 如何才能做到这一点?

Try using reportValidity() 尝试使用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>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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