Solved

onsubmit html form

Posted on 2013-12-05
17
553 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?
0
Comment
Question by:N R
17 Comments
 
LVL 11

Expert Comment

by:MajorBigDeal
ID: 39700115
Use an alert and return false
0
 
LVL 11

Accepted Solution

by:
MajorBigDeal earned 375 total points
ID: 39700116
Like this:

alert('selected too many items'); return false;
0
 
LVL 82

Assisted Solution

by:Dave Baldwin
Dave Baldwin earned 125 total points
ID: 39700129
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
 
LVL 11

Author Comment

by:N R
ID: 39700143
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
 
LVL 11

Author Comment

by:N R
ID: 39700146
Actually I guess it's not more code.  But still curious if it's better to use javascript over the other solution?
0
 
LVL 11

Expert Comment

by:MajorBigDeal
ID: 39700174
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
 
LVL 11

Author Comment

by:N R
ID: 39700178
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
 
LVL 11

Expert Comment

by:MajorBigDeal
ID: 39700183
Can you post your entire code so that I can debug it?
0
Do You Know the 4 Main Threat Actor Types?

Do you know the main threat actor types? Most attackers fall into one of four categories, each with their own favored tactics, techniques, and procedures.

 
LVL 11

Author Comment

by:N R
ID: 39700185
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
 
LVL 11

Assisted Solution

by:MajorBigDeal
MajorBigDeal earned 375 total points
ID: 39700189
In your onsubmit you have to call the function check, like this:

onsubmit="return check();"
0
 
LVL 11

Author Comment

by:N R
ID: 39700200
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
 
LVL 11

Expert Comment

by:MajorBigDeal
ID: 39700201
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
 
LVL 11

Author Comment

by:N R
ID: 39700203
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
 
LVL 11

Assisted Solution

by:MajorBigDeal
MajorBigDeal earned 375 total points
ID: 39700224
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
 
LVL 108

Expert Comment

by:Ray Paseur
ID: 39701323
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
 
LVL 11

Author Comment

by:N R
ID: 39701342
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
 
LVL 11

Author Comment

by:N R
ID: 39701483
Nevermind it works thanks!
0

Featured Post

Threat Intelligence Starter Resources

Integrating threat intelligence can be challenging, and not all companies are ready. These resources can help you build awareness and prepare for defense.

Join & Write a Comment

Although it can be difficult to imagine, someday your child will have a career of his or her own. He or she will likely start a family, buy a home and start having their own children. So, while being a kid is still extremely important, it’s also …
Any business that wants to seriously grow needs to keep the needs and desires of an international audience of their websites in mind. Making a website friendly to international users isn’t prohibitively expensive and can provide an incredible return…
This tutorial walks through the best practices in adding a local business to Google Maps including how to properly search for duplicates, marker placement, and inputing business details. Login to your Google Account, then search for "Google Mapmaker…
The viewer will learn the basics of jQuery, including how to invoke it on a web page. Reference your jQuery libraries: (CODE) Include your new external js/jQuery file: (CODE) Write your first lines of code to setup your site for jQuery.: (CODE)

760 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

18 Experts available now in Live!

Get 1:1 Help Now