Howto increase / decrease Product Quantity in Shopping Cart

It’s very common in E-Commerce design when you bump to a situation where the customer request increase / decrease the quantity by one feature with Up / Down arrow or + / – buttons. Should you bump yourself into one, feel free to grab my snippet and modify to suits yours:

Code

Pleace the code in-style in the HEAD section or in separate JS file and include in HEAD section

function increase_by_one(field) {
 nr = parseInt(document.getElementById(field).value);
 document.getElementById(field).value = nr + 1;
}

function decrease_by_one(field) {
 nr = parseInt(document.getElementById(field).value);
 if (nr > 0) {
   if( (nr - 1) > 0) {
     document.getElementById(field).value = nr - 1;
   }
 }
} 

How to use

Create the Increase / Decrease links or buttons or anything that invoke the JS script with onclick actions. Replace ‘field’ params with the ID of the quantity textfield.

Here is a demo code

<html>
<head>
<script type="text/javascript">
// Quantity spin buttons
function increase_by_one(field) {
 nr = parseInt(document.getElementById(field).value);
 document.getElementById(field).value = nr + 1;
}

function decrease_by_one(field) {
 nr = parseInt(document.getElementById(field).value);
 if (nr > 0) {
   if( (nr - 1) > 0) {
     document.getElementById(field).value = nr - 1;
   }
 }
} 
</script>

<style type="text/css">
#qty1 { width: 30px; }

</style>
</head>
<body>

  <div class="cart-quantity">
	Qty: <input id="qty1" type="text" value="1" name="qty" />
	<button onclick="increase_by_one('qty1');">+</button>
	<button onclick="decrease_by_one('qty1');" />-</button>
  </div>


</body>
</html>
Advertisements

About Jones Lee

Nothing much about me..

2 responses to “Howto increase / decrease Product Quantity in Shopping Cart

  1. dfgdsshdh

    Not working on IE9 Firefox 11

  2. Manish Jadhav

    How to deal with Dynamic id.

    @Html.TextBoxFor(o => o.MenuDetails[i].Qty, new { @id = “Qty_” + i ,@class=”form-control”,@style=”width:50px;”})

    what will be my parameter for increase_by_one() method

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: