在隐藏的单选框/复选框上显示HTML5错误消息/验证 [英] Display HTML5 error message/validation on hidden radio/checkbox

查看:69
本文介绍了在隐藏的单选框/复选框上显示HTML5错误消息/验证的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有CSS定制的单选按钮,该按钮具有必需验证.默认的单选按钮被CSS规则隐藏.

I have CSS-customized radio buttons, which have required validation. The default radio buttons are hidden by CSS rule.

提交表单时,默认验证消息也被隐藏.

When I submit the form, the default validation message is also hidden.

表单如下

在禁用单选按钮时如何显示默认错误消息(例如:请选择选项之一)? (不使用Js的纯HTML/CSS)

How can I display default error message (like: Please select one of the options) while disabling radio buttons? (Pure HTML/CSS without using Js)

input[type="radio"] {
  -webkit-appearance: none;
  -moz-appearance: none;
  appearance: none;
  visibility: hidden;
}

input[type="radio"]:checked +label {
  border: 1px solid blue;
}

<h3>Gender</h3>

<input id="male" type="radio" name="gender" value="male" required>
<label for="male">Male</label>

<input id="female" type="radio" name="gender" value="female" required>
<label for="female">Female</label>

<input id="other" type="radio" name="gender" value="other" required>
<label for="other">Rather not to say</label>

推荐答案

正如@joostS所说,隐藏的单选按钮不会触发本机错误消息.为此,我们需要使用不透明度将其隐藏.我创建了示例示例.

as @joostS said, hidden radio button will not trigger native error message. for that we need to hide it using opacity. I have created sample example.

在我们单击提交按钮提交表单之前,它也不会触发验证.如果您需要验证任何表单元素的"onChange"事件,那么我们需要使用jQuery或Javascript解决方案来实现.

Also it will not trigger validation until we submit the form by clicking on submit button. If you need validation on "onChange" event of any form elements, then we need to use jQuery or Javascript solution to achieve that.

我希望这会有所帮助.

label {
	display: inline-block;
	border: 2px solid #83d0f2;
	padding: 10px;
	border-radius: 3px;
	position: relative;
}

input[type="radio"] {
  opacity: 0;
	position: absolute;
	z-index: -1;
}

input[type="radio"]:checked +label {
  border: 1px solid #4CAF50;
}

input[type="radio"]:invalid +label {
  
}

<h3>Gender</h3>
<form>
	
	
		<input id="male" type="radio" name="gender" value="male" required> 
	<label for="male">Male</label>

	
		<input id="female" type="radio" name="gender" value="female" required> 
	<label for="female">Female</label>

	
		<input id="other" type="radio" name="gender" value="other" required>
	<label for="other">Child</label>

	<input type="submit" />
</form>

这篇关于在隐藏的单选框/复选框上显示HTML5错误消息/验证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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