如何使伪类:无效适用于提交表单后的输入 [英] How to make pseudo class :invalid apply to an input AFTER submitting a form

查看:162
本文介绍了如何使伪类:无效适用于提交表单后的输入的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我创建了一个表单,并决定只用HTML5和一些JS来验证它,而没有任何额外的插件。所以我所需的所有输入都有 required 属性。



以下是CSS让它们看起来很漂亮

  input:无效{b $ b border:2px solid#c15f5f 
}

它设置边框无效输入为红色,即使它们尚未被触摸。

如果在点击提交按钮后出现输入:无效应用,并附带错误消息?

解决方案

当点击提交按钮时,您可以向表单添加一个类并调整您的CSS选择器,使其仅匹配以提交的形式输入字段:

  document.getElementById(submitButton) .addEventListener(click,function(){document.getElementById(testForm)。className =submitted;});  

  form.submitted input:invalid {border:1px solid red;}  

 < form id =testForm>< input type =textrequired>< input type =submitvalue =提交id =submitButton>< / form>  

I have created a form and decided to validate it with just HTML5 and some JS without any additional plugins. So all of my required inputs have required attribute.

Here is the CSS to make them look nice

input:invalid {
    border: 2px solid #c15f5f
}

It sets the border of the invalid inputs to red, even if they haven't been touched yet.

How to make input:invalid apply after clicking submit button, along with the error messages?

解决方案

You can add a class to the form when the submit-button was clicked and adjust your CSS selector so it only matches the input fields in a submitted form:

document.getElementById("submitButton").addEventListener("click", function(){
	document.getElementById("testForm").className="submitted";
});

form.submitted input:invalid{
  border:1px solid red;
}

<form id="testForm">
<input type="text" required>
<input type="submit" value="submit" id="submitButton">
</form>

这篇关于如何使伪类:无效适用于提交表单后的输入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆