JS 验证checkbox的代码怎么写
我的checkbox是PHP动态生成的 比如
- PHP code
$arr=array('b','n','a');foreach ($arr as $v) {switch ($v) {case "a": echo "<label><input type=\"checkbox\" name=\"a\" value=\"1\"/> A </label>"; break;case "b": echo "<label><input type=\"checkbox\" name=\"b\" value=\"1\"/> B </label>"; break;case "c": echo "<label><input type=\"checkbox\" name=\"c\" value=\"1\"/> C </label>"; break;}}JS代码:
- JScript code
function checkform(){ if(!document.form.a.checked && !document.form.b.checked && !document.form.c.checked ) { alert("需要选择至少一个类型"); return false; }}可能生成的HTML没有 <input type=\"checkbox\" name=\"c\" value=\"1\"/>的原因 ,JS不能验证;如果checkbox是固定的HTMP代码就是ABC三个checkbox都有JS验证是没问题,请问我的验证JS应该怎么改????~~
[解决办法]
把每个设置成
"<label><input type=\"checkbox\" class=\"test\" name=\"a\" value=\"1\"/> A </label>";
在每次动态生成的后面,追加上事件,比如$(".test").clik(checkform);
这样的话,每次点击就会调用checkform函数,必须在生成之后才能调用,或者追加事件
[解决办法]
$(".test").click(checkform)用的jQuery触发事件。你的代码可能是没有在checkbox上加监听事件吧。$(".test")就是选取为class为test的所有元素或标签吧。
[解决办法]
你要确定PHP动态生成的checkbox要先于JS验证函数加载。
不然会出错的。