目标:修复下面的代码,并理解为什么关注单选按钮不像关注文本输入框那样工作。
问题:为什么这不起作用:
function isValidRadio(elem, helperMsg) {
var valid = false;
for (var i = 0; i < elem.length; i++) {
if (elem[i].checked) {
return true;
}
}
alert(notice);
setTimeout("focusElement('" + elem.form.name + "', '" + elem.name + "')", 0);
return false;
}
...当这样做时:
function isValidText(elem, notice) {
var str = elem.value;
var re = /.+/;
if(!str.match(re)) {
alert(notice);
setTimeout("focusElement('" + elem.form.name + "', '" + elem.name + "')", 0);
return false;
} else {
return true;
}
}
示例代码:
function focusElement(formName, elemName) {
var elem = document.forms[formName].elements[elemName];
elem.focus();
elem.select();
}
function validateForm(form) {
if (isValidText(form.phone, "Fail.")) {
if (isValidRadio(form.yesNo, "Fail.")) {
return true;
}
return false;
}
}
<form id='myForm' action='/formPage/collectinfo/' method='post' accept-charset='UTF-8' name="myForm">
<input name="phone" type="text" maxlength="14" size="14" />
<input type="radio" name="yesNo" value="Yes"> Yes <input type="radio" name="yesNo" value="No" > No
<input type="submit" value=" Submit " name="Submit" onclick="return validateForm(myForm)" />
详细信息:我正在使用 php/javascript/html,到目前为止,我只在 Chrome 中测试过这部分。表单工作得很好,验证工作直到它点击 isValidRadio。警报运行,但随后 javascript 中断。代码修复会很棒,但我不介意“一生都在钓鱼......”