Reputation: 22270
I'm processing a form with php and I want to add validation on the client side too. I read about.com's tutorial about validating radio buttons with javascript and set up this sample according to its guidelines.
a) Why isn't it showing the alert message?
b) How can I substitute the alert message for some innerHtml text?
<!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>
Upvotes: 1
Views: 2112
Reputation: 2870
Looks like a case issue. Your onclick handler for the submit button is valbutton2(myform);
but the name of the function you are trying to call is actually valButton2
.
With regards to getting the innerHTML, without using a framework it can be kind of ugly. One solution would be to add an id to the labels that contains the id of the corresponding radio button:
<label for="r1" id="lbl-r1"><input type="radio" name="group1" id="r1" value="1" /> button one</label>
Then return a reference to the selected radio button from your second function instead of its value return btn[cnt];
instead of return btn[cnt].value;
. Then you could access the label text using something like the following:
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);
}
}
I've been using jQuery and other frameworks for so long now I'm more than a little rusty at doing this in straight javascript, so this could probably be improved a lot, but you get the idea.
Upvotes: 1