cybertextron
cybertextron

Reputation: 10981

checking a form before submitting - JavaScript

I have the following form:

<html xmlns="http://www.w3.org/1999/xhtml">
<head><meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
  <title>Choose</title>
  <script type="javascript/text">

    function ischecked(){
        var check = document.getElementsByTagName( 'input' );
        for( var i = 0; i < check.length; i++ ){
        if( check[ i ].type == 'radio' && check[ i ].checked ){
            return true;
          }
        }
        return false;
    }

  </script>
</head>

<body>
  <form method="post" enctype="application/x-www-form-urlencoded" onsubmit="ischecked();">
    <h1>Choose</h1>

    <p><input type="radio" name="choose" value="psychology"><font size="5" color="#0033CC">Instant Psychology</font><br>
    <br>
    <input type="radio" name="choose" value="geography"><font size="5" color="#CC0000">Instant Geography</font><br>
    <br>
    <input type="radio" name="choose" value="gastronomy"><font size="5" color="#660033">Instant Gastronomy</font><br>
    <br>
    <input type="submit" name="Submit" value="Go"></p>
  </form>


</body><link rel="stylesheet" type="text/css" href="data:text/css,"></html>

I wanted to make sure one of the radio buttons have been checked before submitting the form. However, it does not work, and the form is submitted anyways. What am I doing wrong here?

Upvotes: 0

Views: 191

Answers (2)

Luca Fagioli
Luca Fagioli

Reputation: 13369

You have to check against the value returned in your validation function directly in the attribute value. That is, in your HTML form declaration

<form method="post" enctype="application/x-www-form-urlencoded" onsubmit="ischecked();">

you should write:

onsubmit="return ischecked();"

instead of:

onsubmit="ischecked();"

Upvotes: 1

SLaks
SLaks

Reputation: 888293

You need to return the result of your function from the inline event handler.

Upvotes: 5

Related Questions