Web Design - Quickly Validate Radio Buttons With JavaScript

When you create a form with radio buttons, you may not always want to specify a default checked field. For instance, if you create an on-line questionnaire, you probably don't want the browser to automatically check 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 below offers the perfect solution to do just that. This code will validate radio buttons when submitted.

  • < head> (Remove space before head)
  • < script language="JavaScript" type="text/javascript"> (Remove space before script)
  • function Validate(frm, btnName) {
  • var btn = frm[btnName]
  • var valid
  • for (var x=0;x
  • valid = btn[x].checked
  • if (valid) {break}}
  • if (!valid) {
  • alert("Please select an answer.")}}
  • < /script>< /head> (Remove space in front of the slashes)
  • < form> (Remove space before form)
  • < input type="radio" name="question1" id="1b1" value="1">Always< /input> (Remove space before input and the slash)
  • < input type="radio" name="question1" id="1b3" value="3">Sometimes< /input> (Remove space before input and the slash)
  • < input type="radio" name="question1" id="1b5" value="5">Never< /input> (Remove space before input and the slash)
  • < div>< input type="button" value="Submit Answer" onclick="validate(this.form, 'question1')"/> (Remove space before div and input)
  • < /div>< /form> (Remove space before slashes)

Go back