Link to home
Create AccountLog in
Avatar of dm06tw
dm06tw

asked on

Simple radio button verification, .php form w/ javascript

Hi There,

I'm working on a .php form and need a simple way to validate that two groups of radio buttons (within loops) are checked. It is not desirable to have either option defaulted, but rather to ensure the user selects both. I'd like to have the form gently (ie not "alert") tell them that they need to complete the form if they try to submit with unselected radio buttons, and then wait until all are selected before moving to the form processing page. Using a js function or .php is equally acceptable.

//////// VERY abbreviated code, showing necessary components
<FORM NAME="results" METHOD="POST" ACTION="/mailrestest.php">
for($i=1; $i<=$matches; $i++){

for($j = 1; $j <= $games; $j++){

<INPUT TYPE="radio" name="results'.$i.$j.'" VALUE="We Won"><FONT FACE="verdana" SIZE="2">We Won</Font>
<INPUT TYPE="radio" name="results'.$i.$j.'" VALUE="We Lost"><FONT FACE="verdana" SIZE="2">We Lost</Font>
<INPUT TYPE="radio" name="results'.$i.$j.'" VALUE="We Tied"><FONT FACE="verdana" SIZE="2">We Tied</Font>

} // End For Loop - Games

<INPUT TYPE="radio" name="spirit'.$i.'" VALUE="1"><FONT FACE="verdana" SIZE="2">1</Font>
<INPUT TYPE="radio" name="spirit'.$i.'" VALUE="1.5"><FONT FACE="verdana" SIZE="2">1.5</Font>
<INPUT TYPE="radio" name="spirit'.$i.'" VALUE="2"><FONT FACE="verdana" SIZE="2">2</Font>
<INPUT TYPE="radio" name="spirit'.$i.'" VALUE="2.5"><FONT FACE="verdana" SIZE="2">2.5</Font>
<INPUT TYPE="radio" name="spirit'.$i.'" VALUE="3"><FONT FACE="verdana" SIZE="2">3</Font>
<INPUT TYPE="radio" name="spirit'.$i.'" VALUE="3.5"><FONT FACE="verdana" SIZE="2">3.5</Font>
<INPUT TYPE="radio" name="spirit'.$i.'" VALUE="4"><FONT FACE="verdana" SIZE="2">4</Font>
<INPUT TYPE="radio" name="spirit'.$i.'" VALUE="4.5"><FONT FACE="verdana" SIZE="2">4.5</Font>
<INPUT TYPE="radio" name="spirit'.$i.'" VALUE="5"><FONT FACE="verdana" SIZE="2">5</Font></TD>

}//End For Loop - Matches

<P ALIGN=CENTER><INPUT TYPE="Submit" Value="Submit">
Avatar of Michel Plungjan
Michel Plungjan
Flag of Denmark image

Quick and brute force:


<script>
var games = new Array()
var matches = new Array();
var nofGames = <? echo $games; ?>
var nofMaches = <? echo $matches; ?>

function game(theRad) {
  games[theRad.name]=theRad.value;
}
function spirit(theRad) {
  matches[theRad.name]=theRad.value;
}
function validate(theForm) {
      document.getElementById('msg').innerHTML="";

  for (var i=0;i<nofMatches;i++) {
    if (matches["spirit"+i]==null) {
      document.getElementById('msg').innerHTML='<span style="color:red">Please check spirit #'+i+'</span>';
      theForm.["spirit"+i].focus();
      return false
    }
    for (var j=0;j<nofGames;j++) {
      if (games["results"+i+j]==null) {
        document.getElementById('msg').innerHTML='<span style="color:red">Please check result #'+i+j+'</span>';
        theForm.["results"+i+j].focus();
        return false
      }
    }
  }
  return true
}

<FORM NAME="results" METHOD="POST" ACTION="/mailrestest.php" onSubmit="return validate(this)">


<INPUT TYPE="radio" name="results'.$i.$j.'" VALUE="We Won" onClick="game(this)"><FONT FACE="verdana" SIZE="2">We Won</Font>
<INPUT TYPE="radio" name="results'.$i.$j.'" VALUE="We Lost" onClick="game(this)"><FONT FACE="verdana" SIZE="2">We Lost</Font>
<INPUT TYPE="radio" name="results'.$i.$j.'" VALUE="We Tied" onClick="game(this)"><FONT FACE="verdana" SIZE="2">We Tied</Font>

} // End For Loop - Games

<INPUT TYPE="radio" name="spirit'.$i.'" onClick="spirit(this)" VALUE="1"><FONT FACE="verdana" SIZE="2">1</Font>
<INPUT TYPE="radio" name="spirit'.$i.'" onClick="spirit(this)" VALUE="1.5"><FONT FACE="verdana" SIZE="2">1.5</Font>
.
.
.
<span id="msg"></span>
<input type="submit">
Why not use dropdowns by the way?
then you only need to check if the select.selectedIndex <1 for each set
I like to use javascript as a php page would need to store the POST variables to rebuild the page.
<FORM NAME="results" METHOD="POST" ACTION="/mailrestest.php" onsubmit="return checkform(no_of_matches, no_of_games);">

put DIV tags around the matches and games radio buttons with an id = 'match$i' / 'game$i$j' then you can use javascript to reference these tags and whats inside them with the following functions:

var tempMatch  = document.getElementById('match'+i); // do the same for games
var tempMatchRadioButtons = tempMatch.getElementsByTagName('INPUT');  // do the same for games

// now you can loop through tempMatchRadioButtons to see if one is selected
// doing the same for games will yield the same result

here is some javascript:

function checkform(matches, games) {
    var i=1;
    var j=1;
    for (i=1; i<=matches; i++) {
        for (j=1; j<=games; j++) {
           
.....

}


hopefully makes some sense!
Avatar of dm06tw
dm06tw

ASKER

It looks okay, but it seems to have thrown off my other js function (which I didn't mention before). The reload function gets the value of one dropdown(league)  and works with mysql to fill a second one (team) based on the league selection. Any idea as to why?

function reload(form)
{
var sport=document.getElementById('sport').value;
var val=form.cat.options[form.cat.options.selectedIndex].value;
self.location='mailformtest.php?sport=' + sport +'&cat=' + val ;
}

** As for why not use dropdowns, we're trying to make the form look consistant with a hardcopy score sheet we're currently using. Our older version of the form (which is what I'm working on improving) had dropdowns but users often ignored them... :(
I would need to see the complete page

Perhaps I introduced an error
Avatar of dm06tw

ASKER

It's Pretty Big... I upped the point value

<?php
//***************************************
// This is downloaded from www.plus2net.com //
/// You can distribute this code with the link to www.plus2net.com ///
//  Please don't  remove the link to www.plus2net.com ///
// This is for your learning only not for commercial use. ///////
//The author is not responsible for any type of loss or problem or damage on using this script.//
/// You can use it at your own risk. /////
//*****************************************

$dbservertype='mysql';
$servername='localhost';
// username and password to log onto db server
$dbusername='';
$dbpassword='';
// name of database
$dbname='';

////////////////////////////////////////
////// DONOT EDIT BELOW  /////////
///////////////////////////////////////
connecttodb($servername,$dbname,$dbusername,$dbpassword);
function connecttodb($servername,$dbname,$dbuser,$dbpassword)
{
global $link;
$link=mysql_connect ("$servername","$dbuser","$dbpassword");
if(!$link){die("Could not connect to MySQL");}
mysql_select_db("$dbname",$link) or die ("could not open db".mysql_error());
}
//////// End of connecting to database ////////
?>

<!doctype html public "-//w3c//dtd html 3.2//en">

<html>

<head>
<title>Submit Results for Perpetual Motion</title>
<meta name="GENERATOR" content="Arachnophilia 4.0">
<meta name="FORMATTER" content="Arachnophilia 4.0">
<SCRIPT language=JavaScript>
function reload(form)
{
var sport=document.getElementById('sport').value;
var val=form.cat.options[form.cat.options.selectedIndex].value;
self.location='mailformtest.php?sport=' + sport +'&cat=' + val ;
}

var games = new Array()
var matches = new Array();
var nofGames = <? echo $games; ?>
var nofMaches = <? echo $matches; ?>

function game(theRad) {
  games[theRad.name]=theRad.value;
}
function spirit(theRad) {
  matches[theRad.name]=theRad.value;
}
function validate(theForm) {
      document.getElementById('msg').innerHTML="";

  for (var i=0;i<nofMatches;i++) {
    if (matches["spirit"+i]==null) {
      document.getElementById('msg').innerHTML='<span style="color:red">Please check spirit #'+i+'</span>';
      theForm.["spirit"+i].focus();
      return false
    }
    for (var j=0;j<nofGames;j++) {
      if (games["results"+i+j]==null) {
        document.getElementById('msg').innerHTML='<span style="color:red">Please check result #'+i+j+'</span>';
        theForm.["results"+i+j].focus();
        return false
      }
    }
  }
  return true
}


</script>
</head>

<body>

<?php
      # matches = 1..5 matches per day
      # games = 1..5 games per match
      # sport='beach' which automatically sets matches to 2 and games to 2
      # sport='ultimate' which automatically sets matches to 2 and games to 1

      if(isset($_GET['sport'])){$sport = $_GET['sport'];}else{$sport = 'unknown';}
      if(isset($_GET['games'])){$games = $_GET['games'];}else{$games = 1;}
      if(isset($_GET['matches'])){$matches = $_GET['matches'];}else{$matches = 2;}

      $games = max(1, min($games, 5));
      $matches = max(1, min($matches, 5));

##DAVE
# if you adding a sports
# Duplicate the 4 lines and set the matches and games appropriately
# Remember that the sport is anything you pass to the script
# link mailform.php?sport='coedwrestling'
# variable $filter makes the dropdown show only leagues from the selected sport

      if($sport == 'ultimate'){
            $games = 1;
            $matches = 2;
            $filter = "where cat_id > 10 and cat_id < 16";
            $points = 17;
      }
      if($sport == 'beach'){
            $games = 2;
            $matches = 2;
            $filter = "where cat_id < 11";
         $points = 27;
   }
      if($sport == 'football'){
            $games = 1;
            $matches = 2;
            $filter = "where cat_id > 15 and cat_id < 18";
         $points = 42;
   }
      if($sport == 'soccer'){
            $games = 1;
            $matches = 2;
            $filter = "where cat_id > 17";
         $points = 10;
   }

print '
<HTML>

<BODY>
';

@$cat=$_GET['cat']; // anything labelled cat or category is referring to league, this is a league variable for the dropdown

///////// Getting the data from Mysql table for first list box//////////
$quer2=mysql_query("SELECT DISTINCT category,cat_id FROM category ".$filter." order by cat_id");
///////////// End of query for first list box////////////

/////// for second drop down list we will check if category is selected else we will display all the subcategory/////
if(isset($cat) and strlen($cat) > 0){
$quer=mysql_query("SELECT DISTINCT subcategory FROM subcategory where cat_id=$cat order by subcategory");
}else{$quer=mysql_query("SELECT DISTINCT subcategory FROM subcategory order by cat_id"); }
////////// end of query for second subcategory drop down list box ///////////////////////////


##DAVE
# This is the text of the title for each sport.  To add another sport
# duplicate the 3 lines 'case ....   print ..... break'
# Then add your sport into the case line and change the text appropriately
      switch ($sport){
      case 'beach':
            print '<P ALIGN=CENTER><B><FONT FACE="verdana" SIZE="2">Report a Score for Guelph Beach Volleyball League</FONT></B><BR>';
            break;
      case 'ultimate':
            print '<P ALIGN=CENTER><B><FONT FACE="verdana" SIZE="2">Report a Score for Guelph Ultimate League</FONT></B><BR>';
            break;
      case 'football':
            print '<P ALIGN=CENTER><B><FONT FACE="verdana" SIZE="2">Report a Score for Guelph Flag Football League</FONT></B><BR>';
            break;
      case 'soccer':
            print '<P ALIGN=CENTER><B><FONT FACE="verdana" SIZE="2">Report a Score for Guelph 6 vs 6 Soccer League</FONT></B><BR>';
            break;


      default:
            print '<P ALIGN=CENTER><B><FONT FACE="verdana" SIZE="2">Report a Score for Perpetual Motion</FONT></B><BR>';
            break;
      }


# DAVE
# The TABLE here is currently 'red' you can fool with it
# BGCOLOR, BORDER, ... however you see fit.
// The enabled variable controls whether you can select teams based on whether you select a league first
$enabled="disabled";

print '
<FORM NAME="results" METHOD="POST" ACTION="/mailrestest.php"
onSumbit="return validate(this)">
<INPUT TYPE="hidden" NAME="games" VALUE="'.$games.'">
<INPUT TYPE="hidden" NAME="matches" VALUE="'.$matches.'">
<INPUT TYPE="hidden" NAME="sport" VALUE="'.$sport.'">
<TABLE>
<TR><TD>
      <TABLE BORDER="1" BGCOLOR="CCCCCC">
            <TR><TD COLSPAN="2"><P ALIGN=CENTER><B><FONT FACE="verdana" SIZE="2">Game Information</B></TD></FONT></TR>
            <TR><TD><FONT FACE="verdana" SIZE="2">Please Select a League: </Font></TD>
            <TD>

';
      //////////        LEAGUE DROPDOWN LIST        /////////
## DAVE, you shouldn't have to edit this at all!

echo "<select name='cat' onchange=\"reload(this.form)\"><option value=''>Select League</option>";
while($noticia2 = mysql_fetch_array($quer2)) {
if($noticia2['cat_id']==@$cat){
$enabled="enabled";
echo "<option selected value='$noticia2[cat_id]'>$noticia2[category]</option>"."<BR>";}
else{echo  "<option value='$noticia2[cat_id]'>$noticia2[category]</option>";}
}
echo "</select>";

//////////////////  This will end the first drop down list ///////////

/////////////////   Start of team dropdown list       ////////////////
print'
      </TD> </TR>

            <TR>            <TD><FONT FACE="verdana" SIZE="2">Team Name:</Font></TD>';
            print "<TD>";
      print "<select name='teamname' ".$enabled."><option value=''>Select Team</option>";
      $second="";
      while($noticia = mysql_fetch_array($quer)) {
      //stores the data to fill the dropdown in one variable, so it can be used for opponent lists as well
      $second.= "<option value='$noticia[subcategory]'>$noticia[subcategory]</option>";
      }
      $second.= "</select>";
      print $second;
      print"</TD>
      </TR>";
      // $second now holds the dropdown data for the team/opponent dropdowns

//////////////      end of team dropdown list           //////////////
      print'
            <TR><TD><FONT FACE="verdana" SIZE="2">Date the Game was Played:</Font></TD>
            <TD><INPUT TYPE="text" NAME="date" VALUE="" SIZE=30>
';

print '
            </TD>
            </TR>
      </TABLE>
</TD></TR>

';

for ($i = 1; $i <= $matches; $i++){
# DAVE
# The Match table can be customized with borders and colors.

print '
      <TR><TD>
      <TABLE BORDER="1" BGCOLOR="CCCCFF">
            <TR><TD COLSPAN="3"><B><P ALIGN=CENTER><FONT FACE="verdana" SIZE="2">Match #'.$i.'</Font></B></TD></TR>

            <TR>
            <TD><FONT FACE="verdana" SIZE="2">Opponent Name:</Font></TD>
            <TD>';
      print "<select name='oppname".$i."' ".$enabled."><option value=''>Select Opponent</option>";
      print $second;
      print'</TD>
      </TR>';
   // ABOVE: The opponent name dropdown is loaded by printing the data stored in "$second"

      for($j = 1; $j <= $games; $j++){
            print '
            <TR>
            <TD><FONT FACE="verdana" SIZE="2">Game '.$j.':</Font></TD>
            <TD>
            <TABLE><TR>';
            
      //The "us" Score
            print'
         <TD><FONT FACE="verdana" SIZE="2">Us: </Font></TD>
         <TD><FONT FACE="verdana" SIZE="2">Score:</Font>
                  <SELECT NAME="scoreus'.$i.$j.'">';

                  //Runs a for loop to load the max number of points based on the sport
                  for ($z=0; $z <= $points; $z++){
         print '<FONT FACE="verdana" SIZE="2"><OPTION VALUE="'.$z.'">'.$z.'</OPTION></Font>';
         }
         print'</td><tr>';

         //The "Them" score
                  print'<TR><TD>
         <FONT FACE="verdana" SIZE="2">Them:</Font></TD>
                  <TD><FONT FACE="verdana" SIZE="2">Score:</Font>
                  <SELECT NAME="scorethem'.$i.$j.'">';
         //for loop, same as above
         for ($x=0; $x <= $points; $x++){
         print '<FONT FACE="verdana" SIZE="2"><OPTION VALUE="'.$x.'">'.$x.'</OPTION></Font>';
         }
         print '</td>';

         //Below is how you set up the radio buttons for win/loss/tie
                  //This loads the array variable 'results' with dummy data, incase the user doesn't enter win/loss/tie
                  //'results'.$i.$j = "None Selected";
      print'<TD>&nbsp;</TD>
                  <TR>
         <TD><FONT FACE="verdana" SIZE="2">Results: </Font></TD>
         <TD><INPUT TYPE="radio" name="results'.$i.$j.'" VALUE="We Won" onClick="game(this)"><FONT FACE="verdana" SIZE="2">We Won</Font>
                  <TD><INPUT TYPE="radio" name="results'.$i.$j.'" VALUE="We Lost" onClick="game(this)"><FONT FACE="verdana" SIZE="2">We Lost</Font>
         <TD><INPUT TYPE="radio" name="results'.$i.$j.'" VALUE="We Tied" onClick="game(this)" checked><FONT FACE="verdana" SIZE="2">We Tied</Font></TD>
         <TD>&nbsp;</TD>
      </TR></TABLE>
            </TD></TR>
            ';
}
print '
            <TR>
            <TD><FONT FACE="verdana" SIZE="2">Spirit Score:</Font></TD>
            <TD><INPUT TYPE="radio" name="spirit'.$i.'" VALUE="1" onClick="spirit(this)"><FONT FACE="verdana" SIZE="2">1</Font>
                  <INPUT TYPE="radio" name="spirit'.$i.'" VALUE="1.5" onClick="spirit(this)"><FONT FACE="verdana" SIZE="2">1.5</Font>
                  <INPUT TYPE="radio" name="spirit'.$i.'" VALUE="2" onClick="spirit(this)"><FONT FACE="verdana" SIZE="2">2</Font>
                  <INPUT TYPE="radio" name="spirit'.$i.'" VALUE="2.5" onClick="spirit(this)"><FONT FACE="verdana" SIZE="2">2.5</Font>
                  <INPUT TYPE="radio" name="spirit'.$i.'" VALUE="3" onClick="spirit(this)"><FONT FACE="verdana" SIZE="2">3</Font>
                  <INPUT TYPE="radio" name="spirit'.$i.'" VALUE="3.5" onClick="spirit(this)"><FONT FACE="verdana" SIZE="2">3.5</Font>
                  <INPUT TYPE="radio" name="spirit'.$i.'" VALUE="4" onClick="spirit(this)"><FONT FACE="verdana" SIZE="2">4</Font>
                  <INPUT TYPE="radio" name="spirit'.$i.'" VALUE="4.5" onClick="spirit(this)"><FONT FACE="verdana" SIZE="2">4.5</Font>
                  <INPUT TYPE="radio" name="spirit'.$i.'" VALUE="5" onClick="spirit(this)"><FONT FACE="verdana" SIZE="2">5</Font></TD>
            </TR>      

            <TR>
            <TD><FONT FACE="verdana" SIZE="2">Comments:</Font></TD>
            <TD><TEXTAREA NAME="comments'.$i.'" COLS=40 ROWS=6></TEXTAREA></TD>
            </TR>
      </TABLE>
      </TD></TR>      
      <TR></TR>
';
}

print '

<TR><TD>
<FONT FACE="verdana" SIZE="2">Submitted by (Name):</Font>
<INPUT TYPE="text" NAME="submitname" SIZE=45>
</TD></TR>

<TR><TD>
<FONT FACE="verdana" SIZE="2">Submitted by (Email):</Font>
<INPUT TYPE="text" NAME="submitemail" SIZE=45>
</TD></TR>
<TR><TD>
<P ALIGN=CENTER><span id="msg"></span>
</TD></TR>
<TR><TD>
<P ALIGN=CENTER><INPUT TYPE="Submit" Value="Submit">
</TD></TR>

</TABLE>

</FORM>
</BODY>
</HTML>
';

?>
erm.. the HTML file? I do not have your backend to supply me with data...

I will have to look tomorrow
Avatar of dm06tw

ASKER

I'm confused... was I asked for more information there? By the way, I'm new to EE and really sorry about the code. Only found out about the "<CODE>" tags recently
Yes you were.

I need to see the view-source html since I do not have your backend to supply me with example data and I do not have time to create example data to run your script.
Avatar of dm06tw

ASKER

i'm hoping what you mean by view-source html is the actual form itself hosted on our site... www.perpetualmotion.org/mailform.php?sport=beach
** as you can see, my temporary (but undesirable) solution was to default the radio button to "tied"

I can dump our db if needed so that you could see it (but since you can view how it works from the form itself and are just trying to work with the radio buttons, i doubt that's needed...)

Thanks for being patient, I can respond a lot quicker now, I was just confused about your other post
Giving the url is great. I will look tomorrow
Thanks

Just running Firefox and change a select I get

Error: document.getElementById("sport") has no properties
Source File: http://www.perpetualmotion.org/mailform.php?sport=beach
Line: 13
Ok here is the fix for the first bug

change

onchange="reload(this.form)"

to

onchange="reload(this)"

and the script to

function reload(theSel) {
  var theForm = theSel.form;
  var sport=theForm.sport.value;
  var val=sel.options[sel.selectedIndex].value;
  self.location='mailform.php?sport=' + sport +'&cat=' + val ;
}

ASKER CERTIFIED SOLUTION
Avatar of Michel Plungjan
Michel Plungjan
Flag of Denmark image

Link to home
membership
Create a free account to see this answer
Signing up is free and takes 30 seconds. No credit card required.
See answer
Avatar of dm06tw

ASKER

excellent! thanks