Pages

Wednesday, May 30, 2012

Validate radio buttons with a quick JavaScript

When you create a form with radio buttons, you may not always want to specify a field that’s selected by default. For instance, if you create an online questionnaire, you probably don’t want the browser to automatically select one of the options. Even so, you’ll, no doubt, want the user to select at least one of the choices before submitting the form. As a result, you’ll need a way to make sure this is the case. The JavaScript function in the XHTML page provided here, offers the perfect solution to do just that:

<html><head>
<script language="JavaScript" type="text/javascript">
function Validate(frm, btnName) {
var btn = frm[btnName]
var valid
for (var x=0;x<btn.length;x++) {
    valid = btn[x].checked
    if (valid) {break}}
if (!valid) {
   alert("Please select an answer.")}}
</script></head>
<body><form>
<input type="radio" name="question1" id="1b1" value="1">Always</input>
<input type="radio" name="question1" id="1b3" value="3">Sometimes</input>
<input type="radio" name="question1" id="1b5" value="5">Never</input>
<div><input type="button" value="Submit Answer" onclick="Validate(this.form, 'question1')"/>
</div></form></body></html>

This code validates radio buttons when the form’s submitted.



No comments:

Post a Comment

Note: Only a member of this blog may post a comment.