We help IT Professionals succeed at work.

onsubmit html form

Nathan Riley
Nathan Riley asked
on
749 Views
Last Modified: 2013-12-06
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?
Comment
Watch Question

Use an alert and return false
This one is on us!
(Get your first solution completely free - no credit card required)
UNLOCK SOLUTION
Dave BaldwinFixer of Problems
CERTIFIED EXPERT
Most Valuable Expert 2014
Commented:
This one is on us!
(Get your first solution completely free - no credit card required)
UNLOCK SOLUTION
Nathan RileyFounder

Author

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?
Nathan RileyFounder

Author

Commented:
Actually I guess it's not more code.  But still curious if it's better to use javascript over the other solution?
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.
Nathan RileyFounder

Author

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?
Can you post your entire code so that I can debug it?
Nathan RileyFounder

Author

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

This one is on us!
(Get your first solution completely free - no credit card required)
UNLOCK SOLUTION
Nathan RileyFounder

Author

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.
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
   }
Nathan RileyFounder

Author

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

This one is on us!
(Get your first solution completely free - no credit card required)
UNLOCK SOLUTION
Most Valuable Expert 2011
Author of the Year 2014

Commented:
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.
https://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.
Nathan RileyFounder

Author

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

Nathan RileyFounder

Author

Commented:
Nevermind it works thanks!
Unlock the solution to this question.
Join our community and discover your potential

Experts Exchange is the only place where you can interact directly with leading experts in the technology field. Become a member today and access the collective knowledge of thousands of technology experts.

*This site is protected by reCAPTCHA and the Google Privacy Policy and Terms of Service apply.

OR

Please enter a first name

Please enter a last name

8+ characters (letters, numbers, and a symbol)

By clicking, you agree to the Terms of Use and Privacy Policy.