I am trying to write a javascript function to validate 3 input fields on my form. The action is to a PHP file, which will INSERT to the db. First, I need to verify that the item number (Eitem) is not blank, to prevent empty records from inserting. Next I have to arrays of checkboxes (playval and ageval which need to have at least one box checked.
FIRST QUESTION: Even when I test it with only the item number validation, I get the alert, but the form posts anyway.
<form action=“update.php” name=“form1” onSubmit=return checkForm(this)">
This is the simple version (with only item number):
<script language =“JavaScript” type=“text/javascript”>
function checkForm(oForm)
{
if (oForm.Eitem.value==“”){
alert (“Cannot proceed without Item Number!”);
oForm.Eitem.focus();
return false;
}
}
</script>
The functions for validating the checkboxes:
function grpMinimum(grp, min, msg)
{
if (typeof grp[0] == ‘undefined’) return true;
var el, i = 0, msg = 'Please choose at least ’ + min + msg;
while (el = grp[i++])
if (el.checked)
if (–min == 0) return true;
alert(msg);
grp[0].focus();
return false;
}
function checkBoxes(oForm)
{
if (!grpMinimum(oForm.elements[‘design_random_selection’], 2, ’ design selections.')) return false;
// additional validation
return true; //all OK
}
So, two questions/issues:
how to keep the form from submitting
how to combine these functions so they are called as one, or put them all into the onSubmit.
I know it’s a lot, but have been searching everywhere to no avail, and cannot see the code in most posts (?)
onsubmit is an event handler for the form tag not the submit button. Returning false will cancel the submit. If you include the event handler in the html tag, it should be of this form:
onsubmit=“return validate();”
However, as shown in the code below, there is no reason to mix javascript code amongst the html tags.
To execute two functions, call a single function that executes both the functions.
Here is an example:
<!DOCTYPE html
PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
xml:lang="en" lang="en">
<head>
<script language="javascript">
<!-- Hide from browsers lacking javascript
window.onload = initialize;
//You have to wait until the page loads before you can
//refer to elements:
function initialize()
{
//assign functions to event handlers(note:
//onsubmit is an event handler for the
//<form> tag not the submit button):
document.f.onsubmit=validate;
}
function validate()
{
//Execute two functions:
f1();
f2();
return false;
}
function f1()
{
alert("inside f1");
}
function f2()
{
alert("inside f2");
}
// End hiding -->
</script>
</head>
<div>hello</div>
<body>
<form name="f" method="post" action="dummy.htm">
<input type="submit" name="b1" value="submit" />
</form>
</body>
</html>