How do I implement a Javascript warning box when my user doesn't fill in a field?

Here's my header:

<script language="JavaScript">
$('#photo_form').submit(function() {
    if($('#photo').val() == ''){
        alert('Please select a photo.');
        return false;
    }
});
</script>

Here's my form:

<form enctype="multipart/form-data" action="buy_now_photo_insert_execute.php" method="POST" id="photo_form">
<table width=100%>
<tr>
<td class="photo_title_field">
<IMG SRC="Photos/crop.php?h=100&w=100&f=<?php echo $vivian_row['glamour_shot']; ?>">
</td>
<td>
<input name="photo" type="file" size="38" id="photo">
</td>
</tr>
<tr>
<td colspan="2" style="text-align:center;"><input type="hidden" name="registration_id" value="<?php echo $vivian_row['id']; ?>">
<input type="submit" src="#" id="submitbutton" value="edit" name="submit">
</td>
</tr>
</table></form>

Open in new window


I want a warning box to come up if my user neglects to select a photo to upload. Something's wrong because the code doesn't fire, but I don't know what's going south.

Thoughts?
brucegustPHP DeveloperAsked:
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

GaryCommented:
Have you included the jquery library (or prototype) - whichever you are referencing using $
0
brucegustPHP DeveloperAuthor Commented:
Hey, Gary!

I'm still playing with this.

The jquery library doesn't appear to be necessary. At least when I fire this code:

<script type='text/javascript'>
function notEmpty(elem, helperMsg){
	if(elem.value.length == 0){
		alert(helperMsg);
		elem.focus();
		return false;
	}
	return true;
}
</script>

<input name="photo" type="file" size="38" id='req1'/>
</td>
</tr>
<tr>
<td colspan="2" style="text-align:center;"><input type="hidden" name="registration_id" value="<?php echo $vivian_row['id']; ?>">
<input type="submit" value="submit" onclick="notEmpty(document.getElementById('req1'), 'Please Enter a Value')" value='Check Field' />
</td>
</tr>
</table>

Open in new window


Problem is, I get the alert, but as soon as you click "OK," the page continues to be submitted, rather than staying on the form.

What am I missing? How do I ensure that if the alert is displayed, the info isn't being submitted?
<script type='text/javascript'>
function notEmpty(elem, helperMsg){
	if(elem.value.length == 0){
		alert(helperMsg);
		elem.focus();
		return false;
	}
	return true;
}
</script>

Open in new window

0
GaryCommented:
Bit confused now because your original code was using, what I presumed  was, the jquery library. But now you are posting vanilla javascript.
Can you post your definitive real code - so I am not going round in circles.
0
Big Business Goals? Which KPIs Will Help You

The most successful MSPs rely on metrics – known as key performance indicators (KPIs) – for making informed decisions that help their businesses thrive, rather than just survive. This eBook provides an overview of the most important KPIs used by top MSPs.

brucegustPHP DeveloperAuthor Commented:
Sorry, Gary!

Here's the entire page. Most of this is probably irrelevant to the issue I'm having, as far as the alert preventing the form from actually being submitted, but I figured it was better giving you the entire picture as opposed to snapshot.

Again, the script is working as far as an alert popping up telling the user they need to submit a photo as opposed to leaving the field blank. But after the user closes the alert box, the form is submitted and that's what I'm trying to prevent in the first place.

So, here you go and thank you so much for your time and willingness to share your expertise.

<?php
/*include 'Mobile_Detect.php';
$detect = new Mobile_Detect();
if ($detect->isMobile()) {
// Any mobile device.
header("Location:mobile/index.php");
exit();
}*/
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title>My Qardboard - "be a name, not a number"</title>
<link href="stylesheet.css" rel="stylesheet" type="text/css" />
<map name="links">
<area shape="rect" coords="12,4,262,53" href="index.php">
<area shape="rect" coords="328,17,436,41" href="description.php">
<area shape="rect" coords="484,20,562,40" href="features.php">
<area shape="rect" coords="625,22,700,38" href="options.php">
<area shape="rect" coords="771,22,847,41" href="buy_now.php">
<area shape="rect" coords="925,20,966,41" href="login.php">
<area shape="rect" coords="1056,23,1128,43" href="contact.php">
<area shape="rect" coords="1194,16,1332,37" href="http://www.brucegust.com" target="_blank">
</map>
<map name="footer">
<area shape="rect" coords="101,27,153,43" href="index.php">
<area shape="rect" coords="266,24,349,39," href="description.php">
<area shape="rect" coords="456,27,521,43" href="features.php">
<area shape="rect" coords="639,32,695,41" href="options.php">
<area shape="rect" coords="810,28,880,42" href="buy_now.php">
<area shape="rect" coords="1005,29,1041,40" href="login.php">
<area shape="rect" coords="1172,33,1230,43" href="contact.php">
</map><script type="text/javascript" src="js/jquery.js"></script>
</head>

<body>
<div id="nav_bar">
	<div id="links"><IMG SRC="images/links.png" usemap="#links" border="0"></div>
</div>
<div id="main_body">

<?php
if(!$_POST['email'] OR !$_POST['first_name'])
{
header("Location:need_email.php");
exit();
}
//check to ensure password and password_confirm fields match
if(!$_POST['password']==$_POST['confirm_password'])
{
header("Location:password_match.php");
exit();
}
include ("carter.inc");
$cxn = mysqli_connect($host,$user,$password,$database)
or die ("couldn't connect to server");

//see if this person is already in the database. If so, simply update the info that's there rather than add another entry

$email=trim($_POST['email']);
$first_name = mysqli_real_escape_string($cxn,(trim($_POST['first_name'])));
$last_name = mysqli_real_escape_string($cxn,(trim($_POST['last_name'])));
$bus_name = mysqli_real_escape_string($cxn,(trim($_POST['bus_name'])));
$title = mysqli_real_escape_string($cxn,(trim($_POST['your_title'])));
$phone = trim($_POST['phone']);
$password = trim($_POST['password']);
$security_question = mysqli_real_escape_string($cxn,(trim($_POST['security_question'])));
$security_answer = mysqli_real_escape_string($cxn,(trim($_POST['security_answer'])));

$michelle = "select id, email from registration where email ='$email'";
$michelle_query=mysqli_query($cxn, $michelle)
or die("Couldn't make Michelle work!");
$michelle_count=mysqli_num_rows($michelle_query);
if($michelle_count>0)
{
$michelle_row=mysqli_fetch_assoc($michelle_query);
extract($michelle_row);
$jorja = "update registration set first_name='$first_name',
last_name='$last_name',
bus_name='$bus_name',
title='$title',
phone='$phone',
email = '$email',
password='$password',
security_question='$security_question',
security_answer='$security_answer',
product_type='$_POST[product_type]'";
	if(!$jorja_query=mysqli_query($cxn, $jorja))
	{
	echo "hello";
	$jorja_error=mysqli_errno($cxn).': '.mysqli_error($cxn);
	die($jorja_error);
	exit();
	}
$novie_id=$michelle_row['id'];
}
else
{
$sweetness = "insert into registration (first_name, last_name, bus_name, title, email, phone, password, security_question, security_answer, product_type) values ('$first_name', '$last_name', '$bus_name', '$title','$email','$phone', '$password', '$security_question', '$security_answer', '$_POST[product_type]')";
$sweetness_query=mysqli_query($cxn, $sweetness);
if(!$sweetness_query)
{
$nuts=mysqli_errno($cxn).': '.mysqli_error($cxn);
die($nuts);
}
$novie_id = $cxn->insert_id;
}

$vivian="select * from registration where id='$novie_id'";
$vivian_query=mysqli_query($cxn, $vivian) 
or die("Couldn't execute vivian");
$vivian_row=mysqli_fetch_assoc($vivian_query);
extract($vivian_row);
?>
<div id="left_body">
<?php
if($vivian_row['product_type']==2)
{
?>
<b>Your "Bulletin Board"</b>
<?php
}
else
{
?>
<b>Your "White Board"</b>
<?php
}
?>
<P>
Alright,<?php echo stripslashes($vivian_row['first_name']); ?>! Let's get your picture.
<P>
<u>Third: upload your picture.</u> </P>
Choose a picture and hit "submit."
<HR>
<P><form enctype="multipart/form-data" action="buy_now_photo_insert_execute.php" method="POST">
<table width=100%>
<tr>
<td class="photo_title_field">
your photo
</td>
<td>
<script type='text/javascript'>
function notEmpty(elem, helperMsg){
	if(elem.value.length == 0){
		alert(helperMsg);
		elem.focus();
		return false;
	}
	return true;
}
</script>
<input name="photo" type="file" size="38" id='req1'/>
</td>
</tr>
<tr>
<td colspan="2" style="text-align:center;"><input type="hidden" name="registration_id" value="<?php echo $vivian_row['id']; ?>">
<input type="submit" value="submit" onclick="notEmpty(document.getElementById('req1'), 'Please Enter a Value')" value='Check Field' />
</td>
</tr>
</table></form>
<HR>
<form action="buy_now_contact_edit.php" method="Post">
<table width=100%>
<tr>
<td colspan="2"><BR>
Check the information below. If you need to make any changes, adjust the appropriate fields and hit "edit."
</td>
</tr>
<tr>
<td colspan="2">
&nbsp;<BR>
</td>
</tr>
<tr>
<td>
your business' name (if applicable)
</td>
<td>
<input type="text" size="50" name="bus_name" value="<?php echo stripslashes($vivian_row['bus_name']); ?>">
</td>
</tr>
<tr>
<td>
your first name<sup><font color="#f50431">*</font></sup>
</td>
<td>
<input type="text" size="50" name="first_name" value="<?php echo stripslashes($vivian_row['first_name']); ?>">
</td>
</tr>
<tr>
<td>
your last name<sup><font color="#f50431">*</font></sup>
</td>
<td>
<input type="text" size="50" name="last_name" value="<?php echo stripslashes($vivian_row['last_name']); ?>">
</td>
</tr>
<tr>
<td>
your title (if applicable [director, manager, publicist etc.])
</td>
<td>
<input type="text" size="50" name="your_title" value="<?php echo stripslashes($vivian_row['title']); ?>">
</td>
</tr>
<tr>
<td>
your email<sup><font color="#f50431">*</font></sup>
</td>
<td>
<input type="text" size="50" name="email" value="<?php echo $vivian_row['email']; ?>">
</td>
</tr>
<tr>
<td>
your phone number
</td>
<td>
<input type="text" size="50" name="phone" value="<?php echo $vivian_row['phone']; ?>">
</td>
</tr>
<tr>
<td>
your password
</td>
<td>
<input type="password" size="50" name="password" value="<?php echo $vivian_row['password']; ?>">
</td>
</tr>
<tr>
<td>
confirm password
</td>
<td>
<input type="password" size="50" name="confirm_password" value="<?php echo $vivian_row['password']; ?>">
</td>
</tr>
<tr>
<td>
security question
</td>
<td>
<select name="security_question">
<option selected><?php echo stripslashes($vivian_row['security_question']); ?><option>
<option>What street did you grow up on?</option>
<option>What's the name of your favorite pet?</option>
<option>Where did you get your first kiss?</option>
<option>___________________________________________</option>
</td>
</tr>
<tr>
<td>
security question answer
</td>
<td>
<input type="text" size="50" name="security_answer" value="<?php echo stripslashes($vivian_row['security_answer']); ?>">
</td>
</tr>
<tr>
<td colspan="2" style="text-align:center;"><BR>
<?php
if($vivian_row['product_type']==2)
{
?>
<input type="hidden" name="product_type" value="2">
<?php
}
else
{
?>
<input type="hidden" name="product_type" value="1">
<?php
}
?><input type="hidden" name="id" value="<?php echo $vivian_row['id']; ?>">
<input type="submit" value="edit"></td>
</tr>
</table></form>
</div>
<div id="right_body">
<?php
if($vivian_row['product_type']==2)
{
?>
<IMG SRC="images/bulletin_board_sample.png" style="float:right;" width="250" border="0">
<?php
}
else
{
?>
<IMG SRC="images/white_board_sample.png" style="float:right;" width="250" border="0">
<?php
}
?>
</div>
<?php require_once('footer.php'); ?>

Open in new window

0
brucegustPHP DeveloperAuthor Commented:
And Gary, just so feel like I'm respecting your time, let me direct you to the line(s) where your talent is needed.

The page you're looking at is inserting the contact information that was submitted a moment ago. The fields that are now presented to the user allow them to confirm / edit what they just entered as well as submit a photo. It's that photo field on line 154 and the script prefacing it beginning on line 144 where I need to make some improvements. Specifically, I don't want the form to be submitted if that photo field is left blank. Right now, I get the alert, but once the user clicks "OK" and closes the alert box, the form is submitted and that's what I need to prevent.

Anxiously awaiting your insight...
0
GaryCommented:
Change your function to this, notice I have removed the return true - the function would return anyway (unless you stop it), but having the return true in there as you had means you are passing control back to the form even when you shouldn't be
<script type='text/javascript'>
function notEmpty(elem, helperMsg){
	if(elem.value.length == 0){
		alert(helperMsg);
		elem.focus();
		return false;
	}
}
</script>

Open in new window

In this bit
<input type="submit" value="submit" onclick="notEmpty(document.getElementById('req1'), 'Please Enter a Value')" value='Check Field' />

add a return, so:
<input type="submit" value="submit" onclick=" return notEmpty(document.getElementById('req1'), 'Please Enter a Value')" value='Check Field' />


p.s.
In HTML5 you do not need to explicitly close self closing elements, so you can remove the / bit.
0

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
brucegustPHP DeveloperAuthor Commented:
That did it!

Thank you, sir!
0
brucegustPHP DeveloperAuthor Commented:
BTW: Gary, I'm needing to do the same thing, but I need to validate two fields and not just one. If you want to weigh in on how I could alter the above script to accommodate two fields, head out to http://www.experts-exchange.com/Programming/Languages/Scripting/JavaScript/Q_28267704.html

Thanks!
0
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
JavaScript

From novice to tech pro — start learning today.