验证单选按钮

时间:2010-08-27 23:50:08

标签: javascript html

我正在使用php处理表单,我也希望在客户端添加验证。我阅读了about.com关于使用javascript验证单选按钮的教程,并根据其指南设置了此示例。

a)为什么不显示警告信息?

b)如何将警报消息替换为某些innerHtml文本?

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html><head>

<meta content="text/html; charset=ISO-8859-1" http-equiv="content-type"><title>validateradio</title>


<script type="text/javascript">


function valButton(btn) {
    var cnt = -1;
    for (var i=btn.length-1; i > -1; i--) {
        if (btn[i].checked) {cnt = i; i = -1;}
    }
    if (cnt > -1)  return btn[cnt].value;
    else          return null;

}




function valButton2(form){

var btn=valButton(form.group1);
if (btn==null){alert('no radio button selected');}
else alert('button value' + btn + 'selected');


}


</script>


</head>


<body style="color: rgb(0, 0, 0); background-color: rgb(255, 255, 255);" alink="#000088" link="#0000ff" vlink="#ff0000"><br>

<form name="myform">


 <label for="r1"><input type="radio"
name="group1" id="r1" value="1" /> button one</label> 

 <label for="r2"><input type="radio"
name="group1" id="r2" value="2" /> button two</label>

 <label for="r3"><input type="radio"
name="group1" id="r3" value="3" /> button three</label> 


<input type="submit" name="submitit" onclick="valbutton2(myform);" value="Validate" />



</form>



</body></html>

1 个答案:

答案 0 :(得分:1)

看起来像一个案例问题。提交按钮的onclick处理程序为valbutton2(myform);,但您尝试调用的函数名称实际为valButton2

关于获取innerHTML,不使用框架,它可能有点难看。一种解决方案是将id添加到包含相应单选按钮的id的标签:

<label for="r1" id="lbl-r1"><input type="radio" name="group1" id="r1" value="1" /> button one</label>

然后从第二个函数返回对所选单选按钮的引用,而不是return btn[cnt];而不是return btn[cnt].value;。然后,您可以使用以下内容访问标签文本:

var id = btn.getAttribute("id");
var lbl = document.getElementById("lbl-" + id);
for (var i = 0; i < lbl.childNodes.length; i++) {
    var n = lbl.childNodes[i];
    if (n.nodeType == 3) {
        alert(n.nodeValue);
    }
}

我一直在使用jQuery和其他框架,现在我在直接的javascript中做这个有点生疏,所以这可能会有很大改进,但你明白了。

相关问题