jQuery for Web Designers - Limit users to a maximum number of clicks on OpenCart checkbox options -

I just recently discovered OpenCart as a very powerful, but easy-to-use PHP based open source ecommerce platform. OpenCart is written in PHP's MVC framework. With OpenCart, you can add products with attributes, options, categories, discounts, and more. It also supports great SEO per product page.

One of my web design clients recent asked me to build them a manageable ecommerce system and I used OpenCart. That was a no brainer. However, she wanted a feature where only 5 options out of of 15 are allowed, so the customer cannot select more than 5. This functionality is not available in OpenCart for options. I either needed to accomplish this with PHP or jQuery and I chose jQuery.

If you have the same need to lock down a maximum number of checkbox options from a list, you can add the code from this hub.

You will access the common.js under \catalog\ javascript\.

Here is the code:

$(document).ready(function() {
	/* Search */

// Global variables
	var idThatWasClicked;
	var overMaxAlert = "Please select no more than ";
	var overMaxdvice = ". If you wish to select other options, please uncheck one of your previously selected options.";

// Code for a maximum of 5 Up Market Sandwiches
	var upmarketSandwichesChecked;
	var upmarketSandwichesMax = 5;
	var upmarketSandwiches = ["option-value-40","option-value-41","option-value-42","option-value-43","option-value-45","option-value-64","option-value-63","option-value-62","option-value-61","option-value-44","option-value-47","option-value-46","option-value-49","option-value-50","option-value-51","option-value-52","option-value-55","option-value-54","option-value-53","option-value-58","option-value-56","option-value-57","option-value-60","option-value-59"];

	$.each(upmarketSandwiches,function()
	{
		$('#' + this).addClass('upmarketSandwiches');
	});

	$('.upmarketSandwiches').click(function()
	{
		idThatWasClicked = $(this).attr('id');
		upmarketSandwichesChecked = 0;
		$.each(upmarketSandwiches, function() {
			if($("#" + this).attr('checked'))
			{
				upmarketSandwichesChecked++;
			}
	   });

		if(upmarketSandwichesChecked > upmarketSandwichesMax)
		{
			window.alert(overMaxAlert + upmarketSandwichesMax + overMaxdvice);
			//$('.upmarketSandwiches').attr('disabled',true);
			$('#' + idThatWasClicked).attr('checked',false);
		}


	});

We start with a blank form of 15 checkboxes.

What this code will do:

This jQuery code is for a restaurant and there is a selection of 15 sandwiches for a catering situation. My client's customer is only allowed to choose 5 from the list.

Under normal OpenCart circumstances, the customer would be able to check all 15 checkboxes, but again, we have to limit them to only 5.

We need jQuery to count all the checked boxes every time any of the checkboxes is clicked. We will only count the checked boxes and voila, we will have a number to compare to our defined maximum.

If the number of checked boxes exceeds our maximum, we will do the following:

  1. Popup an alert telling the customer that they went over.
  2. Remove the check from the checked box and leave it at the maximum.

So how does the above code work?

We have checked 5 boxes so far.

Explanation of the jQuery code

Line 1: Just the normal jQuery call that comes with common.js. I start developing below.

Lines 5 to 12: Declare some initial values for the variables that we will be using in this code.

  • Line 5 - I need to keep track of which checkbox was clicked so we can remove it if the customer goes over the limit.
  • Lines 6 and 7, we simply define an alert message when the maximum has been exceeded and an advice message. You can define these to say anything.
  • Line 10: upmarketSandwichesChecked is the variable that will start from zero and increment every time one of the boxes are checked.
  • Line 11: upmarketSandwichesMax - This variable is the maximum of allowed checked boxes and is compared to the upmarketSandwichesChecked variable on line 30.
  • Line 12: upmarketSandwiches - This is an array that I prepared of all of the option-value-## where ## is the number ID assigned by OpenCart's MySQL database. You need to get these numbers by looking in your page source or at the MySQL database directly, but I can assure you that looking in the page course is easier and faster. These numbers will be different for YOUR website.

Lines 14 to 17 - Since OpenCart does not assign a CSS class to its checkbox options, we can use that to our advantage and have jQuery assign a class to all of your checkboxes using jQuery's each function. Call this class anything you want. We will use this class to iterate over tall of the checkboxes when one of them is clicked.

On line 14, I use the each function to go through each of the IDs in the array and assign the upmarketSandwiches class using jQuery'saddClassfunction to it so I can reference their clicks in line 19.

Lines 19 to 35 - This is where the real work happens.

  • Line 19, I use the click function to see if any of the checkboxes in the upmarketSandwiches class have been clicked.
  • Line 21: I grab the checked boxes ID (assigned by OpenCart) and assign it the idThatWasClickedvariable. We will use this on line 34 to remove its checked status in case that particular checkbox sets us over the limit set by our variable upmarketSandwichesMax .
  • Line 22: We set the upmarketSandwichesChecked to 0 so we start our count from the beginning.
  • Line 23: We start our each function and loop through each element in the upmarketSandwiches class.
  • Line 24: We use a conditional to test the checked attribute and increment the upmarketSandwichesChecked on line 26 if the conditional comes back as true.
  • Line 30: We have a conditional to test if we went over the maximum.
  • Line 32: We show an alert box telling the customer that they went over.
  • Line 34: We remove the check of the checkbox that the customer last clicked. Remember, we assigned idThatWasClicked to the ID of the variable that triggered the whole click function and then use that ID to set the attribute to checked=false.

That's it.



Our simple Javascript popup alert when we exceed 5 boxes checked.

More by this Author


Comments 48 comments

Brianna 5 years ago

Great hub and I also needed this for my OpenCart. Thanks.


Martin Rosales 5 years ago

I am desesperate for some like this.

You can give me please the common.js and show me how i can put in the product page (the call).

I explain what i need:

RADIO option

O option 1

O option 2

O option 3

when you click any RADIO option, open the correspond SELECT option

But if this is not viable, with your code i can put 3 checkbox option GROUPS and force to mark only one.

Please Help Me my email is martinrosales2011@hotmail.com

Thanks


hotwebideas profile image

hotwebideas 5 years ago from New York Author

Hey Martin, no problem. I will email you the common.js, but it is the same as what I posted above in this hub.

You can definitely use my checkbox code from this hub. For the radio option buttons, you would need to add a select element and hide it with CSS and then when someone clicks one of those radio buttons, which you can use EACH to apply addClass, you will reference the ID for that Select element and do a $('select#ID name')css('display','block').

Or you could do a $('select#ID name')show('slow'). Either would work.


psychicdog.net profile image

psychicdog.net 5 years ago

worth looking into this further...thanks HWI


hotwebideas profile image

hotwebideas 5 years ago from New York Author

You're welcome, psychicdog.net. Do you have an ecommerce website with OpenCart?


denysaputra profile image

denysaputra 5 years ago from jakarta

Hi, this is awesome thanks there :)


psychicdog.net profile image

psychicdog.net 5 years ago

No, but I've been toying with building these for clients in my local area (if I ever get the time with a day job and kids!). I have built a number of websites - brochures, a local directory site,fun and tech sites and program in php so this article was spot on HWI.


hotwebideas profile image

hotwebideas 5 years ago from New York Author

denysaputra, glad you like it. You're welcome.

@psychicdog.net - I am flattered. I will be doing some PHP hubs soon.


luiscar16 5 years ago

hi i need exactly like this for my opencart(1.5.1) i follow the instructions but dosent work :( what can i do?

this si my product link: http://createmybar.com/index.php?route=product/product&path=59_60&product_id=53

please help thanks


luiscar16 5 years ago

UPDATE: thanks for this hub my problem was a typo :D


hotwebideas profile image

hotwebideas 5 years ago from New York Author

Thanks, luiscar16. I hope you enjoy the code.


jacharless profile image

jacharless 5 years ago from Between New York and London

Nice. I also use jQuery Simple Cart which is very easy to manipulate/design.

Oddly, I recently used a jQuery .tab solution to do this. It limits the number of steps back or forward based on the data input or selections by the customer. Orinigally, I did it for registration purposes, but it really helps with shopping cart steps also. In essence, if they choose "corned beef sandwich" or "turkey club", it will only allow the NEXT tab to be within these parameters and the selected checkboxes will toggle the relevance.

I am going to see how this code works. Good stuff.


Steveopoly 5 years ago

Where do I find common.js to add this code?


Steve 5 years ago

Nevermind. I found it under catalog/view/javascript.


hotwebideas profile image

hotwebideas 5 years ago from New York Author

Hey jacharless, I will have to check out jQuery Simple Cart.

Steveopoly, The common.js comes with OpenCart and is located in the javascript directory.

Bruce


zz77777 4 years ago

This seems like a great option - but I don't seem to have a common.js file anywhere. And I have a fully functional OpenCart tool installed.

Could this be different in the newer version?


hotwebideas profile image

hotwebideas 4 years ago from New York Author

zz77777, what version of open cart do you have? I have 1.5.0 for the site where I wrote this jQuery.

Also, try this folder: catalog/view/javascript which is where it is located in Open Cart 1.5.0


zz77777 4 years ago

Thanks for responding - I have Version 1.4.9.5. If I go to catalog/view/javascript

...the choices are DD_belatedPNG_0.0.8a-min.js, unitpngfix and jquery.

Perhaps it's in a different file name? Is there a snippet of code I can search for in the files?


hotwebideas profile image

hotwebideas 4 years ago from New York Author

I am not sure. I started using OpenCart at 1.5.x, so as for 1.4.x, I assume there is no common.js. My advice is to upgrade your current installation ;)


zz77777 4 years ago

Thanks - finally upgraded. But how do you assign the variable?

My product name is:

A Variety of Ready to go Sandwiches

...with several options to choose from.

How do I reference "A Variety of Ready to go Sandwiches" in the code? Yours seems to indicate that you simply removed the spaces. Or is that how it is already stored in the database?

Thanks again for your help!


hotwebideas profile image

hotwebideas 4 years ago from New York Author

@zz77777 I did not remove spaces, but only the checkbox attributes. Those options came from the database, but you can also look in the HTML page source for the assigned option numbers. Everyone's numbers will be different.


zz77777 4 years ago

Thanks - but I'm still not seeing how this should be configured. Here's an example of what I've added:

Code for a maximum of 5 Up Market Sandwiches

var A Variety of Ready to go SandwichesChecked;

var A Variety of Ready to go SandwichesMax = 3;

var A Variety of Ready to go Sandwiches = ["option-value-1","option-value-2","option-value-3","option-value-4"];

"A Variety of Ready to go Sandwiches" is the only format I see when searching the database. I'm guessing that is not how it should appear in the code? Since I can't get it to work in the cart, after the code is added.


hotwebideas profile image

hotwebideas 4 years ago from New York Author

I think I get it now. Yes, you are right, I removed all the spaces. Adding "var A Variety of Ready to go SandwichesChecked" will not work in javascript; that is not coded right. Make sure your variable has no spaces.

Instead, use " var AVarietyofReadytogoSandwichesChecked" and so forth.


zz77777 4 years ago

Thank you soooo much - It's working!!!!! woooohooooo!


hotwebideas profile image

hotwebideas 4 years ago from New York Author

Glad it's working. You also just learned a new Javascript rule. LOL


WhoopAss 4 years ago

Great script and works GREAT!!!

I was able to get what you have posted working.

But I'm wondering if you can help me to take it few steps further with it.

I would like to know if we can make it so we can...

1. Make it so it'll also have a Min pop-up msg. As is now, if the Max for an option is set to 5, than you get a msg when you try to select 6th... Can we also give a Min value to the option? Let's say if the Min is 3, and you only have 2 selected and try to add to cart. It'll give you a pop-up msg about the Min-requirement and not add to cart nor clear current 2 options selected until all requirements are meet.

2. Can we also give it a function to randomly select from given option values? Ex. Let's say we have 10 pizza toppings as options on the list and want to give the customer an option to select 5 toppings them self or randomly select 5 from the 10.

Thanks in advance for your reply and once again great work with current script!!!


hotwebideas profile image

hotwebideas 4 years ago from New York Author

Hey WhoopAss, glad you like the script. Yes, we can do #1 and that one may be easier that the max popup, because we do not really need that listener every time there is a click.

#1 would work on the Add To Cart button instead of a checkbox click, because the script has no way of knowing whether or not you reach that minimum until you try to add to cart. There is a jQuery command to count all the clicked elements from one class, in this case, $('.upmarketSandwiches') and I think we can use something like:

var checked = $('.upmarketSandwiches').length;

if (checked less than 3) {alert('Select at least 3')};

It could work like that.

For #2 with the random selections, I will have to look that up and get right back to you.

Bruce


WhoopAss 4 years ago

Thanks for your quick reply...

Sorry for this newbie question but I guess I must ask it since I am a newbie... =(

Following is what I currently got and works great... But when I try adding your code from above to the $('#button-cat') section, nothing new happens... Will you please point me to the right direction~

var idThatWasClicked;

var pizzaCrustOverMaxAlert = "Please select just ";

var pizzaCrustOverMaxdvice = " Crust type. If you wish to select a different crust, first uncheck the one you currently have selected.";

var pizzaCrustChecked;

var pizzaCrustMax = 1;

var pizzaCrust = [

"option-value-156",

"option-value-157",

"option-value-158"

];

$.each(pizzaCrust,function()

{

$('#' + this).addClass('pizzaCrust');

});

$('.pizzaCrust').click( function()

{

idThatWasClicked = $(this).attr('id');

pizzaCrustChecked = 0;

$.each(pizzaCrust, function() {

if($("#" + this).attr('checked'))

{

pizzaCrustChecked++;

}

});

if(pizzaCrustChecked 'greater than' pizzaCrustMax)

{

window.alert(pizzaCrustOverMaxAlert + pizzaCrustMax + pizzaCrustOverMaxdvice);

//$('.pizzaCrust').attr('disabled',true);

$('#' + idThatWasClicked).attr('checked',false);

}

});

var overMaxAlert = "Please select no more than ";

var overMaxdvice = " toppings. If you wish to select a different topping, please uncheck one of your previously selected toppings.";

var pizzaToppingsChecked;

var pizzaToppingsMax = 5;

var pizzaToppings = [

"option-value-201",

"option-value-202",

"option-value-203",

"option-value-204",

"option-value-205",

"option-value-206",

"option-value-207",

"option-value-208",

"option-value-209",

"option-value-210",

"option-value-211",

"option-value-212",

"option-value-213",

"option-value-214"

];

$.each(pizzaToppings,function()

{

$('#' + this).addClass('pizzaToppings');

});

$('.pizzaToppings').click( function()

{

idThatWasClicked = $(this).attr('id');

pizzaToppingsChecked = 0;

$.each(pizzaToppings, function() {

if($("#" + this).attr('checked'))

{

pizzaToppingsChecked++;

}

});

if(pizzaToppingsChecked 'greater than' pizzaToppingsMax)

{

window.alert(overMaxAlert + pizzaToppingsMax + overMaxdvice);

//$('.pizzaToppings').attr('disabled',true);

$('#' + idThatWasClicked).attr('checked',false);

}

});

function clear_form_elements(ele) {

$(ele).find(':input').each(function() {

switch(this.type) {

case 'password':

case 'select-multiple':

case 'text':

case 'textarea':

$(this).val('');

break;

case 'checkbox':

case 'radio':

this.checked = false;

}

});

};

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

var opcionesbuild = $('div.option');

clear_form_elements(opcionesbuild);

});

Thanks again...


WhoopAss 4 years ago

I was able to resolve the Min qty issue with your help above. Thanks again for that.

Still hoping I can get some help with the random selection issue... Thanks again...


hotwebideas profile image

hotwebideas 4 years ago from New York Author

Woohoo, whoopass. Very cool. I am still working on the random.

Here is some quick javascript help on the random. Use Math.floor((Math.random()*X)+1)) where X is the number of items you want selected randomly. I think you said 5 above, so make it Math.floor((Math.random()*5)+1))

Then, look in my code in this hub for the jQuery each function. You will basically cycle through all of the checkboxes with a certain CSS class and then put them into an array. Shuffle your array of items and voila, you will have your random checkboxes.


WhoopAss 4 years ago

Bruce,

Thanks for your update.

I'll try it out as you've informed and get back with you with what I end up with...

Thanks again for following up with me...

James...


hotwebideas profile image

hotwebideas 4 years ago from New York Author

No problem, James. jQuery has really helped me to open a can of whoopass in my programming projects. LOL


WhoopAss 4 years ago

Supz Bruce,

How are you?

I'm still kinda stuck on the Min & Max issues on my little project and need your advice on it again please.

All the warnings are working fine, not being able to select more than the max selection qty is working fine.

Issue 1.

If I add to cart with less than the min qty selected, I do get the min selection qty warning but it still gets added to the cart, with current selections (less than required min).

Q. Need help to make it not to add to cart if required min and max are not meet.

Please refer to below link...

http://creativespacesinc.com/=ICATER=/index.php?ro.../product&path=62&product_id=81

Issue 2.

With above modifications made on common.js, seems it's effecting all other items as well. Min & Max warnings pop up on all other items, with out these these options.

Q. Is there a way to isolate your min & max option selection function only to the items with those options?

Please refer to below link...

http://creativespacesinc.com/=ICATER=/index.php?ro.../product&path=61&product_id=67

Issue 3.

Haven't even got started on the random portion yet. With both my brain cells working on the min & max issue, when I looked again at your last note regarding the random... I just got a "Huhhhh???" out of my head...

Issue 4.

Greatly need your help again on above issues, please advice how I too can open up a can o' WhoopAss on it... LOL Tks...


WhoopAss 4 years ago

Hummm

Seems links didn't get proper posted above... Here they are again...

http://creativespacesinc.com/=ICATER=/index.php?ro.../product&path=62&product_id=81

http://creativespacesinc.com/=ICATER=/index.php?ro.../product&path=61&product_id=67


WhoopAss 4 years ago

Hummm X 100000

creativespacesinc.com/=ICATER=/index.php?route=product/product&path=62&product_id=81

creativespacesinc.com/=ICATER=/index.php?route=product/product&path=61&product_id=67


hotwebideas profile image

hotwebideas 4 years ago from New York Author

Yeah, I can click on those links. Sometimes the links get cut off.


WhoopAss 4 years ago

Were you able to get to the links?

I'll try re-posting...

http://creativespacesinc.com/=ICATER=/index.php?ro.../product&path=62&product_id=81

http://creativespacesinc.com/=ICATER=/index.php?ro.../product&path=61&product_id=67


hotwebideas profile image

hotwebideas 4 years ago from New York Author

Hey James, I will go through some of these links today.


WhoopAss 4 years ago

Bruce,

Thanks...

Here's some update...

I've found your page regarding the min qty and played around with it a bit.

Was able to get the min option qty requirement to work when adding to cart, but still have an issue of other products requesting for the same option values even when the options doesn't apply to them.

Seems your string ?php } elseif($_GET['product_id']==69) { ? is suppose to control the individual products to options but when I include it I get no response from the page at all... Hope you can make better sense of this than I can and will wait for your update... Thanks again...


WhoopAss 4 years ago

Supz again Bruce,

How are you?

After some poking around with your codes, I was finally able to get the min and max per item to work properly. Thanks again for your help to get me this far...

Now to figure out about the random issue... T.T


WHoopAss 4 years ago

Uh oh...

I'm back to the min & max issue again...

Seems if I add another item with same options but with different min & max qty requirements, new item doesn't work as the first...


WhoopAss 4 years ago

Bruce,

Seems I'm totally getting this forum page messy, sorry about that...

Again after some poking around I was able to figure out why the min & max option qty wasn't working on new items... Swinging back to the random issue again...


googlingfacebook 4 years ago

hmm works for me


hotwebideas profile image

hotwebideas 4 years ago from New York Author

Excellent, googlingfacebook!


hoodlaces 3 years ago

Thanks for the script, it does wonders! Question though, I'm trying to add code that makes them choose exactly 4, and using your script for no more than 4, only when they go to click the "add cart" it goes a little haywire, any suggestions for the following code? (With out me being able to show you the LESSTHAN sign on my comment?

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

if(hoodlaceColorsChecked LESSTHAN 4){

window.alert("Please choose at least 4 colors");

}

});

THANK YOU!


Var 2 years ago

what do i set my variables? This isn't working for me its messing up my theme.


hotwebideas profile image

hotwebideas 2 years ago from New York Author

Var, did you copy the code verbatim? Please post your code here.


dowfyhtf 2 years ago

第二行开始为正文

购买欢迎登录我们的网站http://cysoft.taobao.com .

联系QQ:2248491535

邮箱地址:2248491535@qq.com

杭州承影软件工作室

seo群发软件专卖

6v8 n029p

    Sign in or sign up and post using a HubPages Network account.

    0 of 8192 characters used
    Post Comment

    No HTML is allowed in comments, but URLs will be hyperlinked. Comments are not for promoting your articles or other sites.


    Click to Rate This Article
    working