在最简单的情况下,我建议(请记住,我不同意您正在做的事情(强迫用户做出选择)或(可怕的)领先和强制性问题的可用选择) :
$('form').submit(function(e){
// in this version we're only using it once, so caching may not be necessary
var self = $(this),
// finds the radio input elements:
radios = self.find('input[type="radio"]'),
/* iterates over the radio elements, creates an array of their names,
discards the duplicates: */
groups = $.unique(radios.map(function(){
return this.name;
}).get()),
// gets all the checked radio elements:
checked = radios.filter(function(){ return this.checked; });
/* if the checked length is not equal to the number of 'groups',
there are some left unchecked: */
return checked.length === groups.length ? true : false;
});
JS 小提琴演示。
笔记:
HTML:已更正为以下内容:
<form action="#" method="post">
<table>
<tbody>
<tr>
<td>
<label for="">Close all liquor shops near and on the National Highways. This will also reduce drunken driving on Highways.</label>
</td>
<td>Yes
<input type="radio" name="close" value="1" />No
<input type="radio" name="close" value="2" />
</td>
</tr>
<tr>
<td>
<label for="">Electronic watch on the National Highways to check speed limit of vehicles. Speed governors should also be installed in the vehicles.</label>
</td>
<td>Yes
<input type="radio" name="ewatch" value="1" />No
<input type="radio" name="ewatch" value="2" />
</td>
</tr>
<tr>
<td>
<label for="">Data base of road accidents on National Highways and effective data collection mechanism.</label>
</td>
<td>Yes
<input type="radio" name="data_collection" value="1" />No
<input type="radio" name="data_collection" value="2" />
</td>
</tr>
<tr>
<td>
<label for="">Stricter punishment for traffic offenders on the Highways and license cancellation of repeat offenders. There should be an online review of license status.</label>
</td>
<td>Yes
<input type="radio" name="punishment" value="1" />No
<input type="radio" name="punishment" value="2" />
</td>
</tr>
<tr>
<td>
<label for="locality">People should follow lane system. It will lead to a reduction in the number of accidents</label>
</td>
<td>Yes
<input type="radio" name="follow" id="follow" />No
<input type="radio" name="follow" id="follow" />
</td>
</tr>
</tbody>
</table>
<button type="submit">Submit</button>
</form>
重复id
的 s 已被删除,checked
属性已被删除(由于您要强制用户交互,因此不提供预先检查的选项,这没有任何意义);我单独留下了空for
属性,但s 应该是/文本(因为这是将被单击以与可用选项交互的内容。这将需要每个label
属性都是唯一的(就像 HTML规范一样),或者你可以简单地嵌套在元素内,给出如下内容:input
yes
no
id
input
input
label
<label>Yes <input type="radio" name="close" value="1" /></label>
<label>No <input type="radio" name="close" value="2" /></label>
参考: