我有一个包含多组复选框的表单(除其他外)。其中一些组是强制字段(至少需要在该组中选中一个复选框)。
我能够判断一个组是否选中了复选框,但我没有强制执行。另外,我还需要获得一个长字符串,其中包含所选复选框(Es)的值。我需要一个字符串,如果用户检查,比如来自group1的前3个复选框,字符串为:
“零-1
该代码是我原代码的简化版本。下面是jFiddle:http://jsfiddle.net/QyY2P/1/
此外,为了您的方便,我还包括以下代码:
jQuery
function countChecked() {
//Group 1
var n = $("#group1 input:checked").length;
$("#count").text(n + (n <= 1 ? " is" : " are") + " checked!");
$("#group1 input:checked").each(function() {
txt += ($(this).val() + " | ");
$("#selection1").text(txt);
alert($(this).val() + " | ");
});
//Group 2
var n = $("#group2 input:checked").length;
$("#count").text(n + (n <= 1 ? " is" : " are") + " checked!");
$("#group2 input:checked").each(function() {
txt += ($(this).val() + " | ");
$("#selection3").text(txt);
alert($(this).val() + " | ");
});
}
countChecked();
$(":checkbox").click(countChecked);<form>
<div id="group1">
<p> *Please select a box (Mandatory)</p>
<input type="checkbox" name="ckb_unit[]" value="zero" />
<input type="checkbox" name="ckb_unit[]" value="1 val" />
<input type="checkbox" name="ckb_unit[]" value="2 val" />
<input type="checkbox" name="ckb_unit[]" value="3 val" />
<input type="checkbox" name="ckb_unit[]" value="4 val" />
</div>
<div id="group2">
<p>Please select a box</p>
<input type="checkbox" name="ckb_unit[]" value="zero" />
<input type="checkbox" name="ckb_unit[]" value="A" />
<input type="checkbox" name="ckb_unit[]" value="B" />
<input type="checkbox" name="ckb_unit[]" value="C" />
<input type="checkbox" name="ckb_unit[]" value="D" />
</div>
<div id="group3">
<p>*Please select a box (Mandatory)</p>
<input type="checkbox" name="ckb_unit[]" value="zero" />
<input type="checkbox" name="ckb_unit[]" value="1 A" />
<input type="checkbox" name="ckb_unit[]" value="2 B" />
<input type="checkbox" name="ckb_unit[]" value="3 C" />
<input type="checkbox" name="ckb_unit[]" value="4 D" />
</div>
</form>
<!-- For debugging purposes -->
<br/>
<div id="count"></div>
<div id="selection1"></div>
<div id="selection3"></div>PS。我是一个初学者,也许你注意到了我的不那么优雅的编码>_<。
发布于 2012-03-07 00:22:29
您可以强制执行以下操作:当用户点击submit时,检查n是否为0,然后以某种方式吸引用户的注意(例如,附加错误消息)。我说的是这件事
var n = $("#group1 input:checked").length;看一看JSFiddle,您似乎没有将txt声明为变量,所以这对我来说是可行的:
//Group 1
var txt = ""; // initialise txt with an empty string, so you can append to it later
var n = $("#group1 input:checked").length;
$("#count").text(n + (n <= 1 ? " is" : " are") + " checked!");
$("#group1 input:checked").each(function() {
txt += ($(this).val() + " | ");
$("#selection1").text(txt);
alert($(this).val() + " | ");
});https://stackoverflow.com/questions/9593696
复制相似问题