I have a simple form on a website that contains two radio buttons, and I have added some Javascript form validation for when the neither of the radio buttons are clicked. (thanks SO) However when the user clicks the okay button the page is redirected to the “process” page for the form. I would prefer the behavior of just reloading the page or closing the alert box when the user clicks the “ok” button in the alert box.
To further see what I’m talking about you can go to chrisrjones.com which should redirect you to chrisrjones.com/splash.php then click enter. (without selecting a radio button) An alert box should appear, and once the okay button is pressed, the page redirects to the form process page (not what I want).
<!DOCTYPE html>
<html lang="en">
<head>
<title>chrisRjones.com - Splash</title>
<?php
function getImagesFromDir($path) {
$images = array();
if ( $img_dir = @opendir($path) ) {
while ( false !== ($img_file = readdir($img_dir)) ) {
// checks for gif, jpg, png
if ( preg_match("/(\.gif|\.jpg|\.png)$/", $img_file) ) {
$images[] = $img_file;
}
}
closedir($img_dir);
}
return $images;
}
function getRandomFromArray($ar) {
mt_srand( (double)microtime() * 1000000 ); // php 4.2+ not needed
$num = array_rand($ar);
return $ar[$num];
}
/////////////////////////////////////////////////////////////////////
// This is the only portion of the code you may need to change.
// Indicate the location of your images
$root = '';
// use if specifying path from root
//$root = $_SERVER['DOCUMENT_ROOT'];
$path = 'pics/';
// End of user modified section
/////////////////////////////////////////////////////////////////////
// Obtain list of images from directory
$imgList = getImagesFromDir($root . $path);
$img = getRandomFromArray($imgList);
?>
<!-- begin google analytics PHP include -->
<?php include_once("analyticstracking.php") ?>
<!-- end google analytics PHP include -->
<!-- Javascript radiobutton form validation -->
<script type="text/javascript">
function valForm(form) {
var btn1 = parseInt(form.splash.value, 10) || 0;
btn = (btn1 )
if (btn < 3) {
alert('You either like splash pages or hate em, choose one ...please');
return false; }
else {
alert('Button value ' + btn + ' selected');
}
}
</script>
<!-- Javascript radiobutton form validation END -->
</head>
<body>
<img src="<?php echo $path . $img ?>" alt="" width="640" height="auto" />
<h1>Hello Javascript redirection.</h1><br />
<p>
<form name="tosplashornottosplash" action="splash-process.php" method="post">
Splash pages are stupid
<input type="radio" name="splash" value="false" /> No
<input type="radio" name="splash" value="true" /> Yes
<input type="submit" name="formSubmit" onClick="valForm(tosplashornottosplash)" value="Enter" />
</form>
</body>
</html>
return false from valform in situations you want to stay on the same page.
for example:
You may also need to change your markup as follows adding the
returnstatement.