如何为我的单选按钮和下拉框创建验证?我是否需要在顶部创建<script>
功能?
<tr>
<td class="alt"><label for="period"><b>Transaction Period:</b> </label></td>
<td><input type="radio" name="period" value="current">Current Month<br>
<input type="radio" name="period" value="current_first">Last 1 Month and Current Month<br>
<input type="radio" name="period" value="current_second">Last 2 Months and Current Month</td>
</tr>
<td class="alt"><label for="type"><b>Type: </b></label></td>
<td>
<input type="radio" name="type" value="both">Credit and Debit<br>
<input type="radio" name="type" value="credit">Credit Only<br>
<input type="radio" name="type" value="debit">Debit Only
</td>
<tr>
<td class="alt"><label for="sort"><b>Sort According To: </b></label></td>
<td> <select name="sort">
<option value="latest">Latest Transaction First</option>
<option value="earliest">Earliest Transaction First</option>
<option value="codes">Transaction Codes</option>
</select>
</td>
</tr>
答案 0 :(得分:1)
要突出显示无效输入,请使用:invalid
伪类。这在older browsers中不起作用,但是较新的浏览器都支持在输入上使用它。对于输入,您必须添加required
属性,并且您需要在其标签周围添加标记(例如<span>
),以便此工作:
新的HTML代码:
<table>
<tr>
<td class="alt">
<label for="period"><b>Transaction Period:</b>
</label>
</td>
<td>
<input type="radio" required name="period" value="current"><span>Current Month</span>
<br>
<input type="radio" required name="period" value="current_first"><span>Last 1 Month and Current Month</span>
<br>
<input type="radio" required name="period" value="current_second"><span>Last 2 Months and Current Month</span>
</td>
</tr>
<td class="alt">
<label for="type"><b>Type: </b>
</label>
</td>
<td>
<input type="radio" required name="type" value="both"><span>Credit and Debit</span>
<br>
<input type="radio" required name="type" value="credit"><span>Credit Only</span>
<br>
<input type="radio" required name="type" value="debit"><span>Debit Only </span>
</td>
<tr>
<td class="alt">
<label for="sort"><b>Sort According To: </b>
</label>
</td>
<td>
<select name="sort" required>
<option value="" selected disabled>Please select an option</option>
<option value="latest">Latest Transaction First</option>
<option value="earliest">Earliest Transaction First</option>
<option value="codes">Transaction Codes</option>
</select>
</td>
</tr>
</table>
<强> CSS:强>
input:invalid + span {
background:#F99;
}
select:invalid {
color:#F55;
}
这个:invalid
伪类将选择一个输入元素:
type="number"
,并且输入的输入不符合特定输入类型的值<select>
,或者没有其中一个单选按钮的无线电输入与选定的pattern
或max
等属性,输入与输入的模式不匹配,或超过最大值。如果任何输入仍为:invalid
,即使按下提交按钮,也不会提交表单。 (simple example)