onsubmit html form

I'm trying to check a rule that if false an alert box pops up on submit and gives a message.  The user can then only select ok and fix the issue and the submit does not happen.

The condition that needs to be met is if $totalqty > $qty then pop up the alert box with message they need to fix before they can submit.

I've tried this:

if($totalqty > $qty)
{ echo '<form method="post" action="#" onsubmit="return confirm('You\'ve selected too many items please remove some before continuing.');">';
}
else
{
echo '<form method="post" action="#">';
}

Open in new window


The above allows the user to hit ok or cancel, I don't want them to be able to continue until they fix the issue.  So is there a way for the alert box to just have an OK button and it not submit?
LVL 12
Nathan RileyFounder/CTOAsked:
Who is Participating?
 
MajorBigDealConnect With a Mentor Commented:
Like this:

alert('selected too many items'); return false;
0
 
MajorBigDealCommented:
Use an alert and return false
0
 
Dave BaldwinConnect With a Mentor Fixer of ProblemsCommented:
Here's a little demo page that works to show how this is normally done in javascript.
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
 "http://www.w3.org/TR/html4/loose.dtd">

<html>
<head>
<title>Form Check</title>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<script type="text/javascript">
<!--
function check() {
	var nmbr = document.getElementById("number").value;
	if (nmbr > 5){
		alert("the number is too high");
		return false;
		}
	return true;
	}

// -->
</script>
</head>
<body>
<h1>Form Check</h1>
<form action="#" method="get" onsubmit="check();">
<input type="text" name="number" id="number" value=""><br>
<input type="submit" name="submit" value="submit">
</form>

</body>
</html>

Open in new window

0
The new generation of project management tools

With monday.com’s project management tool, you can see what everyone on your team is working in a single glance. Its intuitive dashboards are customizable, so you can create systems that work for you.

 
Nathan RileyFounder/CTOAuthor Commented:
Thanks for both solutions guys!

What's the advantage to using the javascript?  Seems like a lot more code to do the same thing?  

I'm not familiar with it though so I assume there is an advantage?
0
 
Nathan RileyFounder/CTOAuthor Commented:
Actually I guess it's not more code.  But still curious if it's better to use javascript over the other solution?
0
 
MajorBigDealCommented:
Both solutions are javascript.  I just gave you the snippet that you could put inside the quotes of the onsubmit event in the example code you posted.  Dave's code also uses an alert and return false but I think he is also trying to help you to make your validation code more organized by moving it into a function instead of doing it directly in the event definition.
0
 
Nathan RileyFounder/CTOAuthor Commented:
Got it thanks.

I went with his option and implemented it now.  I needed to check against some of the values from the input field so worked better this way.

For some reason after I hit ok on the pop up the submit is still going through and not stopping.  Is there something missing from the code above?
0
 
MajorBigDealCommented:
Can you post your entire code so that I can debug it?
0
 
Nathan RileyFounder/CTOAuthor Commented:
It's a piece of woocommerce plugin so not sure if this helps:
<?php
/**
 * The template for displaying product content within loops.
 *
 * Override this template by copying it to yourtheme/woocommerce/content-product.php
 *
 * @author 		WooThemes
 * @package 	WooCommerce/Templates
 * @version     1.6.4
 */

if ( ! defined( 'ABSPATH' ) ) exit; // Exit if accessed directly

global $product, $woocommerce_loop;

// Store loop count we're currently on
if ( empty( $woocommerce_loop['loop'] ) )
	$woocommerce_loop['loop'] = 0;

// Store column count for displaying the grid
if ( empty( $woocommerce_loop['columns'] ) )
	$woocommerce_loop['columns'] = apply_filters( 'loop_shop_columns', 4 );

// Ensure visibility
if ( ! $product || ! $product->is_visible() )
	return;

// Increase loop count
$woocommerce_loop['loop']++;

// Extra post classes
$classes = array();
if ( 0 == ( $woocommerce_loop['loop'] - 1 ) % $woocommerce_loop['columns'] || 1 == $woocommerce_loop['columns'] )
	$classes[] = 'first';
if ( 0 == $woocommerce_loop['loop'] % $woocommerce_loop['columns'] )
	$classes[] = 'last';

//Code to calculate the quantities
$maxqtyorder = $_GET['qty'];
?>
<script type="text/javascript">
    function check() {
        var nmbr = document.getElementById("quantity1334").value;
        if (nmbr > <?php echo $maxqtyorder; ?>){
            alert("the number is too high");
            return false;
        }
        return true;
    }
</script>
<li <?php post_class( $classes ); ?>>

	<?php do_action( 'woocommerce_before_shop_loop_item' ); ?>

	<a href="<?php the_permalink(); ?>">

		<?php
			/**
			 * woocommerce_before_shop_loop_item_title hook
			 *
			 * @hooked woocommerce_show_product_loop_sale_flash - 10
			 * @hooked woocommerce_template_loop_product_thumbnail - 10
			 */
			do_action( 'woocommerce_before_shop_loop_item_title' );
		?>

		<h3><?php the_title(); ?></h3>

		<?php
			/**
			 * woocommerce_after_shop_loop_item_title hook
			 *
			 * @hooked woocommerce_template_loop_price - 10
			 */
			do_action( 'woocommerce_after_shop_loop_item_title' );
		?>

	</a>


<?php 

global $woocommerce, $product;

if ( ! $product->is_purchasable() ) return;
?>

<?php
	// Availability
	$availability = $product->get_availability();

	if ($availability['availability']) :
		echo apply_filters( 'woocommerce_stock_html', '<p class="stock ' . esc_attr( $availability['class'] ) . '">' . esc_html( $availability['availability'] ) . '</p>', $availability['availability'] );
    endif;
?>

<?php if ( $product->is_in_stock() ) : ?>

	<?php do_action('woocommerce_before_add_to_cart_form'); ?>
	
		
														<?php echo $product->get_price_html(); ?>
	<form class="cart" method="post" enctype='multipart/form-data' onsubmit="check();">

	 	<?php do_action('woocommerce_before_add_to_cart_button'); ?>

	 	<?php
	 		if ( ! $product->is_sold_individually() )
	 			woocommerce_quantity_input( array(
	 				'min_value' => apply_filters( 'woocommerce_quantity_input_min', 1, $product ),
	 				'max_value' => apply_filters( 'woocommerce_quantity_input_max', $product->backorders_allowed() ? '' : $product->get_stock_quantity(), $product )
	 			) );
	 	?>

	 	<input type="hidden" name="add-to-cart" value="<?php echo esc_attr( $product->id ); ?>" />
	 	<button type="submit" class="single_add_to_cart_button button alt"><?php echo apply_filters('single_add_to_cart_text', __( 'Add to cart', 'woocommerce' ), $product->product_type); ?></button>
	
		<div class="quantity">
            <input type='button' value='-' class='qtyminus' field='quantity1<?php echo esc_attr( $product->id ); ?>' />
            <input type='text' id='quantity1<?php echo esc_attr( $product->id ); ?>' value='1' class='qty' name="quantity"/>
			<input type='button' value='+' class='qtyplus' field='quantity1<?php echo esc_attr( $product->id ); ?>' />
		</div>

	 	<?php do_action('woocommerce_after_add_to_cart_button'); ?>

	</form>

	<?php do_action('woocommerce_after_add_to_cart_form'); ?>

<?php endif; ?>







</li>

Open in new window

0
 
MajorBigDealConnect With a Mentor Commented:
In your onsubmit you have to call the function check, like this:

onsubmit="return check();"
0
 
Nathan RileyFounder/CTOAuthor Commented:
Ah thanks, one last question.  I'm not sure if you noticed in the example above I hardcoded the "id" of the element for testing.

On my page the id's are all named "quantity" then appended is the product number.  Is there a way to make the javascript work with them all?

I tried:
var nmbr = document.getElementById("quantity*").value;

Open in new window



No go.
0
 
MajorBigDealCommented:
One way would be to use the name tag instead of the id tag.  As you know, all id must be unique but that is not so for name.  You could give them all the name "quantity" and then process the entire list like this:

var elements = document.getElementsByName("quantity");
for (var i=0; i<elements.length; i++) {
   // do something to each element
   }
0
 
Nathan RileyFounder/CTOAuthor Commented:
Not sure if a typo above or I understood wrong.  Edited the code, but still a no go.

<?php
/**
 * The template for displaying product content within loops.
 *
 * Override this template by copying it to yourtheme/woocommerce/content-product.php
 *
 * @author 		WooThemes
 * @package 	WooCommerce/Templates
 * @version     1.6.4
 */

if ( ! defined( 'ABSPATH' ) ) exit; // Exit if accessed directly

global $product, $woocommerce_loop;

// Store loop count we're currently on
if ( empty( $woocommerce_loop['loop'] ) )
	$woocommerce_loop['loop'] = 0;

// Store column count for displaying the grid
if ( empty( $woocommerce_loop['columns'] ) )
	$woocommerce_loop['columns'] = apply_filters( 'loop_shop_columns', 4 );

// Ensure visibility
if ( ! $product || ! $product->is_visible() )
	return;

// Increase loop count
$woocommerce_loop['loop']++;

// Extra post classes
$classes = array();
if ( 0 == ( $woocommerce_loop['loop'] - 1 ) % $woocommerce_loop['columns'] || 1 == $woocommerce_loop['columns'] )
	$classes[] = 'first';
if ( 0 == $woocommerce_loop['loop'] % $woocommerce_loop['columns'] )
	$classes[] = 'last';

//Code to calculate the quantities
$maxqtyorder = $_GET['qty'];
?>
<script type="text/javascript">
    function check() {
        var nmbr = document.getElementsByName("quantity").value;
        for (var i=0; i<elements.length; i++) {
        if (nmbr > <?php echo $maxqtyorder; ?>){
            alert("the number is too high");
            return false;
        }
      }
        return true;
    }
</script>
<li <?php post_class( $classes ); ?>>

	<?php do_action( 'woocommerce_before_shop_loop_item' ); ?>

	<a href="<?php the_permalink(); ?>">

		<?php
			/**
			 * woocommerce_before_shop_loop_item_title hook
			 *
			 * @hooked woocommerce_show_product_loop_sale_flash - 10
			 * @hooked woocommerce_template_loop_product_thumbnail - 10
			 */
			do_action( 'woocommerce_before_shop_loop_item_title' );
		?>

		<h3><?php the_title(); ?></h3>

		<?php
			/**
			 * woocommerce_after_shop_loop_item_title hook
			 *
			 * @hooked woocommerce_template_loop_price - 10
			 */
			do_action( 'woocommerce_after_shop_loop_item_title' );
		?>

	</a>


<?php 

global $woocommerce, $product;

if ( ! $product->is_purchasable() ) return;
?>

<?php
	// Availability
	$availability = $product->get_availability();

	if ($availability['availability']) :
		echo apply_filters( 'woocommerce_stock_html', '<p class="stock ' . esc_attr( $availability['class'] ) . '">' . esc_html( $availability['availability'] ) . '</p>', $availability['availability'] );
    endif;
?>

<?php if ( $product->is_in_stock() ) : ?>

	<?php do_action('woocommerce_before_add_to_cart_form'); ?>
	
		
														<?php echo $product->get_price_html(); ?>
	<form class="cart" method="post" enctype='multipart/form-data' onsubmit="return check();">

	 	<?php do_action('woocommerce_before_add_to_cart_button'); ?>

	 	<?php
	 		if ( ! $product->is_sold_individually() )
	 			woocommerce_quantity_input( array(
	 				'min_value' => apply_filters( 'woocommerce_quantity_input_min', 1, $product ),
	 				'max_value' => apply_filters( 'woocommerce_quantity_input_max', $product->backorders_allowed() ? '' : $product->get_stock_quantity(), $product )
	 			) );
	 	?>

	 	<input type="hidden" name="add-to-cart" value="<?php echo esc_attr( $product->id ); ?>" />
	 	<button type="submit" class="single_add_to_cart_button button alt"><?php echo apply_filters('single_add_to_cart_text', __( 'Add to cart', 'woocommerce' ), $product->product_type); ?></button>
	
		<div class="quantity">
            <input type='button' value='-' class='qtyminus' field='quantity1<?php echo esc_attr( $product->id ); ?>' />
            <input type='text' id='quantity1<?php echo esc_attr( $product->id ); ?>' value='1' class='qty' name="quantity"/>
			<input type='button' value='+' class='qtyplus' field='quantity1<?php echo esc_attr( $product->id ); ?>' />
		</div>

	 	<?php do_action('woocommerce_after_add_to_cart_button'); ?>

	</form>

	<?php do_action('woocommerce_after_add_to_cart_form'); ?>

<?php endif; ?>







</li>

Open in new window

0
 
MajorBigDealConnect With a Mentor Commented:
Sorry, my previous example did not explain how to access the individual elements in the list.  Try something like the following.  I didn't actually run this, it is just to give you the idea but it should be close.

       
 var elements = document.getElementsByName("quantity");
        for (var i=0; i<elements.length; i++) {
        var nmbr = elements[i].value;
        if (nmbr > <?php echo $maxqtyorder; ?>){
            alert("the number is too high");
            return false;
        }
        }
        return true;

Open in new window

0
 
Ray PaseurCommented:
You might benefit from an understanding of the client/server relationship.  PHP runs on the server, sends the HTML to the client and is complete and dormant before the (human) client sees the web page.
http://www.experts-exchange.com/Web_Development/Web_Languages-Standards/A_11271-Understanding-Client-Server-Protocols-and-Web-Applications.html

It follows that any "editing" done in the client Javascript must be redone in the PHP action= script after the form is submitted.  JavaScript is for the comfort and convenience of your (human) client.  PHP is used to validate the input in order to protect the integrity of your data model.

On the client side, jQuery is often used for form validation.  A Google search for "jquery form validation" will turn up many good examples.

In JavaScript, a function that is run onSubmit can control whether the client will submit the HTTP request.  If the function returns false, the form will not be submitted.
0
 
Nathan RileyFounder/CTOAuthor Commented:
Does else if work the same in there? Maybe it needs to be an or statement somehow.

I needed to add another check in the javascript, but doesn't seem to be working:
<script type="text/javascript">
    function check() {
        var elements = document.getElementsByName("quantity");
        var qtycheck = document.getElementById("qtycheck").value;
        for (var i=0; i<elements.length; i++) {
            var nmbr = elements[i].value;
            if (nmbr > <?php echo $maxqtyorder; ?>){
                alert("You've selected more treats than your package allows.");
                return false;
            }
            else if (nmbr > qtycheck){
                alert("You've selected more treats than your package allows.");
                return false;
            }
        }
        return true;
    }
</script>

Open in new window

0
 
Nathan RileyFounder/CTOAuthor Commented:
Nevermind it works thanks!
0
All Courses

From novice to tech pro — start learning today.