ArtsAutosBooksBusinessEducationEntertainmentFamilyFashionFoodGamesGenderHealthHolidaysHomeHubPagesPersonal FinancePetsPoliticsReligionSportsTechnologyTravel
  • »
  • Business and Employment»
  • E-Commerce & How to Make Money Online

jQuery code to enable OpenCart Ecommerce Users To Force Minimum Options To Be Selected When Adding To Cart

Updated on July 5, 2011

I have started using Open Cart, which is an amazing ecommerce software written in open source PHP for web site owners and web design firms. Open Cart is one of the easiest ecommerce systems to use, in my opinion and does not have a big learning curve.

As some of you know, I have a web design client who requires several options for each project that change dynamically. I wrote a hub a few weeks ago offering jQuery code that forces the user to pick a certain number of product options and not to go over that maximum. That hub was at http://hubpages.com/hub/jquery-code-for-OpenCart-checkbox-options-Limit-users-to-a-maximum-number-of-clicks

Now, my client has asked me for the opposite: She needs Open Cart to force a mimimum number of options to be set by her online customers, so for instance, if there are 20 options each with a checkbox, at least have to be selected. I cannot use the same jQuery code as in my other hub that caps the number of options at a maximum and can be detected by clicking on checkboxes. There is no way for the checkbox system to detect whether a minimum has been set. Instead, we need to equip the "Add To Cart" button to count the number of checkboxes clicked and see if the count meets the minimum. Then, if the number of clicked checkboxes has not reached the minimum, we need to halt the Add To Cart function and display a dialog box alert to the user letting them know that they still need to click more boxes.

Here is the code:


$('#button-cart').bind('click', function() {

	var valid = true;
	var invalidMessage = ""

	<?php } elseif($_GET['product_id']==69) { ?>
		var itemsChecked = 0;
		var itemsMin = 2;
		var itemsName = "cream cheeses";
		var items = ["option-value-22","option-value-23","option-value-24","option-value-25"];
		$.each(items,function()
		{
			if($("#" + this).attr('checked'))
			{
				itemsChecked++;
			}
		});
		if(itemsChecked < itemsMin)
		{
			invalidMessage = invalidMessage + 'Please select ' + itemsMin + " " + itemsName + ".\n";
			valid=false;
		}

	<?php } elseif($_GET['product_id']==67) { ?>
		var itemsChecked = 0;
		var itemsMin = 3;
		var itemsName = "baked items";
		var items = ["option-value-73","option-value-74","option-value-75","option-value-76","option-value-77"];
		$.each(items,function()
		{
			if($("#" + this).attr('checked'))
			{
				itemsChecked++;
			}
		});
		if(itemsChecked < itemsMin)
		{
			invalidMessage = invalidMessage + 'Please select ' + itemsMin + " " + itemsName + ".\n";
			valid=false;
		}


	<?php } elseif($_GET['product_id']==65) { ?>
		var itemsChecked = 0;
		var itemsMin = 3;
		var itemsName = "baked items";
		var items = ["option-value-15","option-value-16","option-value-17","option-value-18","option-value-19"];
		$.each(items,function()
		{
			if($("#" + this).attr('checked'))
			{
				itemsChecked++;
			}
		});
		if(itemsChecked < itemsMin)
		{
			invalidMessage = invalidMessage + 'Please select ' + itemsMin + " " + itemsName + ".\n";
			valid=false;
		}

	<?php }  ?>

	if(valid==false)
	{
		window.alert(invalidMessage);
	} else {

	$.ajax({

Since Open Cart uses the MVC (Model Viewer Controller) framework, we have to do this with one of our viewers and add jQuery to it. In this case, we will be editing the product.tpl file under:

\catalog\views\template\product.tpl (this may be different for each Open Cart installation), but you definitely need the product.tpl view file.

You will need to edit the jQuery code starting at the line: $('#button-cart').bind('click', function() - This code in the view is where the Add To Cart button does its magic and you need to intercept that magic with the code in this hub.

On Lines 3 and 4, you will initiate some jQuery variables:

  • valid = true will allow the Ajax code to execute if all the minimums have been met.
  • invalidMessage is the message that gets built when we pop up our alert box telling the user that they did not meet the minimum.

<?php if($_GET['product_id']==84) { ?> - This line is PHP and will be used to create jQuery on the fly. The 84 is different for everyone. You get that number by looking in the URL of your product page. The URL will be product_id=## where ## is a different number for everyone.

  • var itemsChecked = 0;
    This line starts our checkbox click count at zero. It will increment when we loop through the checked checkboxes.
  • var itemsMin = 2;
    This is our minimum. You can set this to any number that you need for the number of clicked checkboxes to be checked. These two variables will be checked against each other.
  • var itemsName = "item name"
    Change item name to the name of your item.
  • var items = ["option-value-22","option-value-23","option-value-24","option-value-25"];
    This is an array of your options. You can get your exact numbers from the MySQL database or by looking at the source code of the generated HTML
  • Now, we look through all the checkboxes and increment the itemsChecked variable if jQuery determines that the checkbox is checked.

$.each(items,function(){if($("#" + this).attr('checked')){itemsChecked++;}});

  • Finally, these last couple of lines will compare the number of checked boxes against the minimum (variable itemsMin) and do an IF conditional to display the message and set the valid variable to false, which will block the ajax from submitting the items to the shopping cart.


if(itemsChecked < itemsMin){invalidMessage = invalidMessage + 'Please select ' + itemsMin + " " + itemsName + ".\n";valid=false;}
You can wrap the Open Cart .Ajax call in this code:if(valid==false){window.alert(invalidMessage);} else {
This code will block the ajax from working if valid=false.

Comments

    0 of 8192 characters used
    Post Comment

    • hotwebideas profile image
      Author

      Bruce Chamoff 4 years ago from New York

      Thanks, Pamela, sorry for the delay. I have been off of Hubpages for a while and am trying to get back. I do custom work, so feel free to comment if you still see this. I know it has been over a year.

    • profile image

      jimmymob 4 years ago from Kenya

      Hi, Thanks for the tutorial, I have the problem of having a maximum limit of the number of a particular product in cart. Can you give me the previous tutorial about the maximum number of clicks. The link you provided above does not work.

      Thanks in advance.

    • profile image

      Pamela 5 years ago

      I so need help with this exact thing...do you do custom work?

    • hotwebideas profile image
      Author

      Bruce Chamoff 5 years ago from New York

      Hi Ivan. The quantity field does not need its own jQuery. There is a setting to force the minimum built into the OpenCart admin settings for the specific products you need that minimum on.

    • profile image

      Ivan 5 years ago

      This looks great - but how can we apply this to options with quantity fields, not checkboxes?

    working

    This website uses cookies

    As a user in the EEA, your approval is needed on a few things. To provide a better website experience, hubpages.com uses cookies (and other similar technologies) and may collect, process, and share personal data. Please choose which areas of our service you consent to our doing so.

    For more information on managing or withdrawing consents and how we handle data, visit our Privacy Policy at: "https://hubpages.com/privacy-policy#gdpr"

    Show Details
    Necessary
    HubPages Device IDThis is used to identify particular browsers or devices when the access the service, and is used for security reasons.
    LoginThis is necessary to sign in to the HubPages Service.
    Google RecaptchaThis is used to prevent bots and spam. (Privacy Policy)
    AkismetThis is used to detect comment spam. (Privacy Policy)
    HubPages Google AnalyticsThis is used to provide data on traffic to our website, all personally identifyable data is anonymized. (Privacy Policy)
    HubPages Traffic PixelThis is used to collect data on traffic to articles and other pages on our site. Unless you are signed in to a HubPages account, all personally identifiable information is anonymized.
    Amazon Web ServicesThis is a cloud services platform that we used to host our service. (Privacy Policy)
    CloudflareThis is a cloud CDN service that we use to efficiently deliver files required for our service to operate such as javascript, cascading style sheets, images, and videos. (Privacy Policy)
    Google Hosted LibrariesJavascript software libraries such as jQuery are loaded at endpoints on the googleapis.com or gstatic.com domains, for performance and efficiency reasons. (Privacy Policy)
    Features
    Google Custom SearchThis is feature allows you to search the site. (Privacy Policy)
    Google MapsSome articles have Google Maps embedded in them. (Privacy Policy)
    Google ChartsThis is used to display charts and graphs on articles and the author center. (Privacy Policy)
    Google AdSense Host APIThis service allows you to sign up for or associate a Google AdSense account with HubPages, so that you can earn money from ads on your articles. No data is shared unless you engage with this feature. (Privacy Policy)
    Google YouTubeSome articles have YouTube videos embedded in them. (Privacy Policy)
    VimeoSome articles have Vimeo videos embedded in them. (Privacy Policy)
    PaypalThis is used for a registered author who enrolls in the HubPages Earnings program and requests to be paid via PayPal. No data is shared with Paypal unless you engage with this feature. (Privacy Policy)
    Facebook LoginYou can use this to streamline signing up for, or signing in to your Hubpages account. No data is shared with Facebook unless you engage with this feature. (Privacy Policy)
    MavenThis supports the Maven widget and search functionality. (Privacy Policy)
    Marketing
    Google AdSenseThis is an ad network. (Privacy Policy)
    Google DoubleClickGoogle provides ad serving technology and runs an ad network. (Privacy Policy)
    Index ExchangeThis is an ad network. (Privacy Policy)
    SovrnThis is an ad network. (Privacy Policy)
    Facebook AdsThis is an ad network. (Privacy Policy)
    Amazon Unified Ad MarketplaceThis is an ad network. (Privacy Policy)
    AppNexusThis is an ad network. (Privacy Policy)
    OpenxThis is an ad network. (Privacy Policy)
    Rubicon ProjectThis is an ad network. (Privacy Policy)
    TripleLiftThis is an ad network. (Privacy Policy)
    Say MediaWe partner with Say Media to deliver ad campaigns on our sites. (Privacy Policy)
    Remarketing PixelsWe may use remarketing pixels from advertising networks such as Google AdWords, Bing Ads, and Facebook in order to advertise the HubPages Service to people that have visited our sites.
    Conversion Tracking PixelsWe may use conversion tracking pixels from advertising networks such as Google AdWords, Bing Ads, and Facebook in order to identify when an advertisement has successfully resulted in the desired action, such as signing up for the HubPages Service or publishing an article on the HubPages Service.
    Statistics
    Author Google AnalyticsThis is used to provide traffic data and reports to the authors of articles on the HubPages Service. (Privacy Policy)
    ComscoreComScore is a media measurement and analytics company providing marketing data and analytics to enterprises, media and advertising agencies, and publishers. Non-consent will result in ComScore only processing obfuscated personal data. (Privacy Policy)
    Amazon Tracking PixelSome articles display amazon products as part of the Amazon Affiliate program, this pixel provides traffic statistics for those products (Privacy Policy)