I am using javascript to display an error when user click on form submit button if the number entered is not in between min and max. The issue is when you click submit button the form will submit regardless. Can you please look at the code below and tell me what I need to add. I need to prevent form from submitting if the min and max condition is not fulfilled.
this is my PHP codes
<div class="clearfix"></div>
<form action="store_items.php" method="post" name="cartform">
<div class="col-12 form-group">
<div class="row">
<div class="col-3">
<input type="hidden" name="cart_name" value="<?php echo $row['product_title']; ?>">
<input type="hidden" name="cart_image" value="<?php echo $row['product_photo']; ?>">
<input id="quantity"type="number" name="cart_qty" step="1" class="form-control text-center" onchange="restrictValue(this,<?php echo $min; ?>, <?php echo $max; ?>)">
<small class="float-right"><?php echo $row['product_unit']; ?></small>
<input type="hidden" name="cart_unit" value="<?php echo $row['product_unit']; ?>">
<input type="hidden" name="cart_price" value="<?php echo $row['product_price']; ?>">
<input type="hidden" name="product_id" value="<?php echo $row['id']; ?>">
<input type="hidden" name="seller_id" value="<?php echo $row['seller_id']; ?>">
</div>
<div class="col-9">
<input id="addtocart" class="btn btn-block addtocart" type="submit" value="Add to cart" name="addtocart" <?php if($row['product_status'] == 0) echo 'disabled="disabled"'; ?> >
</div>
</div>
</div>
</form>
this is the javascript
<script type="text/javascript">
function restrictValue(inputElement,minimum,maximum)
{
let value = inputElement.value;
if (value < minimum) {
value = minimum;
alert('Your order has not reach the minimum order quantity');
return false;
}
if (value > maximum) {
value = maximum;
alert('Your order has exceed the avaliable stock');
return false;
}
inputElement.value = value;
}
</script>
You don't need to prevent form submission! You can specify the min
and max
attribute on <input type="number">
and it will prevent users from entering in anything outside those bounds!
<input id="quantity"type="number" name="cart_qty" step="1" class="form-control text-center" min="<?php echo $min; ?>" max="<?php echo $max; ?>">
But, if you really want to prevent form submission...
<form onsubmit="doValidate">
...
</form>
<script>
function doValidate(event) {
event.preventDefault();
// validate your inputs
};
</script>