Improve company productivity with a Business Account.Sign Up

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 659
  • Last Modified:

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?
0
Nathan Riley
Asked:
Nathan Riley
4 Solutions
 
MajorBigDealCommented:
Use an alert and return false
0
 
MajorBigDealCommented:
Like this:

alert('selected too many items'); return false;
0
 
Dave BaldwinFixer 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
What Kind of Coding Program is Right for You?

There are many ways to learn to code these days. From coding bootcamps like Flatiron School to online courses to totally free beginner resources. The best way to learn to code depends on many factors, but the most important one is you. See what course is best for you.

 
Nathan RileyFounderAuthor 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 RileyFounderAuthor 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 RileyFounderAuthor 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 RileyFounderAuthor 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
 
MajorBigDealCommented:
In your onsubmit you have to call the function check, like this:

onsubmit="return check();"
0
 
Nathan RileyFounderAuthor 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 RileyFounderAuthor 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
 
MajorBigDealCommented:
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 RileyFounderAuthor 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 RileyFounderAuthor Commented:
Nevermind it works thanks!
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

Join & Write a Comment

Featured Post

Free Tool: SSL Checker

Scans your site and returns information about your SSL implementation and certificate. Helpful for debugging and validating your SSL configuration.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

Tackle projects and never again get stuck behind a technical roadblock.
Join Now