Example form that checks for empty fields on submit:
<html> <head> <title>Check input field test</title> <script language = "JavaScript"> function checkFields() { //alert("Checking'" + myform.LastName.value + "'"); if ( myform.LastName.value == "" ) { alert("Must enter a last name"); return false; } if ( myform.FirstName.value == "" ) { alert("Must enter a first name"); return false; } return true; } </script> </head> <body> <form name="myform" onsubmit="return checkFields();" action="http://www.mrsherry.com/submit.php" > <P>First Name: <input type=text name="FirstName"> <P>Last Name: <input type=text name="LastName"> <input type="submit" name="Submit" value="Submit Form"> </form> </body> </html>
Example form that checks for missing radio button selections
<HTML> <HEAD> <TITLE>Requiring an entry</TITLE> <SCRIPT language=Javascript type=text/javascript> <!-- Hide script from old browsers // function to determine whether ANY of the radio buttons in this array of // ..buttons is checked. function radioCheck(obj) { // Assume none of the radio buttons associated with the name 'AorB' // ..are checked. var radio_choice = false; // The object myForm.AorB is an array of buttons. The array is from // ..myForm.AorB[0] to myForm.AorB[numberOfButtons-1]. So if there are // ..10 buttons, they are 0..9 // at this point, obj contains the object of the array of buttons, so // ..if we would have used myForm.AorB.length outside the function, // ..we use obj.length inside. // Loop from zero to the one minus the number of radio button selections for (counter = 0; counter < obj.length; counter++) { // If a radio button has been selected it will return true // (If not it will return false) if (obj[counter].checked) { // if any one of them is checked then our original // ..assumption changes. radio_choice = true; } } return radio_choice; } // function to check all fields in my form. function fieldCheck() { // check to see if ANY of the radio buttons with this name are checked radio_choice = radioCheck(myForm.AorB); // see if any buttons are checked. if (!radio_choice) { // If there were no selections made display an alert box alert("Please select a AorB") return (false); } return true; } // End hiding script from old browsers --> </SCRIPT> </HEAD> <BODY> <FORM name=myForm onsubmit="return fieldCheck();" action=http://www.mrsherry.com/submit.php method=post> Pick one of the following: <P><INPUT type=radio value="A" name="AorB">A <P><INPUT type=radio value="B" name="AorB">B <P><INPUT type=submit value="Submit This Form"> </FORM> </BODY> </HTML>