DZone Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

Snippets has posted 5883 posts at DZone. View Full User Profile

UI For Quantity Fields: Enable Only If Checkboxes Are Checked

10.09.2009
| 2851 views |
  • submit to reddit
        // This is code for Enabling Quantity fields in a form if checkboxes next to them are checked.
// The quantity fields are initially unchecked
// The submit button is enabled if >=1 checkboxes is checked
// This is a way of making sure a consumer knows they are buying something etc etc..



	   	var checkcount = 0;

		$(document).ready(function(){
			 $("form").submit(function () { 
				
				
				 return true; 

			});
			 $('#first-quantity').attr('name','disabled');
			 $('#i1').attr('name','disabled');
			 //$('#i2').attr('name','item_2');
			//lets make sure our checkboxes are ALWAYS unchecked when the page loads
			$('#first-checkbox').removeAttr('checked');
			$('#second-checkbox').removeAttr('checked');
			
			//lets make sure our submit button is ALWAYS disabled when the page loads
			//$('#store-submit').attr({'disabled':'disabled'});
			$('#store-submit').removeAttr('disabled');

			//if product checkbox state changes
			$('#first-checkbox').change(function(){

			   //if the user is checking the box
			   if ( $('#first-checkbox').is(':checked') )
			   {
					//keep count of checkboxes checked
					checkcount++;
					 
				   	//enable things
				   	$('#first-quantity').removeAttr('disabled');
				   	//$('#store-submit').removeAttr('disabled');
			   }

			   //if the user is unchecking the box
			   if ( $('#first-checkbox').attr('checked')==false )
			   {
				 	//keep count of checkboxes checked
				   	checkcount--;
				   
				   //disable things
				   $('#first-quantity').attr({'disabled':'disabled'});
			       	if(checkcount < 1){
				       	
			       		//disable submit button
			       		//$('#store-submit').attr({'disabled':'disabled'});
						
					}
			   }
			   
			});	//end $('first-checkbo...change...

			//if product checkbox state changes
			$('#second-checkbox').change(function(){

				//if the user is checking the box
				if ($('#second-checkbox').is(':checked'))
			    {

					//keep count of checkboxes checked
					checkcount++;
					
					//enable things
			     	$('#second-quantity').removeAttr('disabled');
			     	//$('#store-submit').removeAttr('disabled');
			    }

			    if ($('#second-checkbox').attr('checked')==false)
			    {

			    	//keep count of checkboxes checked
			    	checkcount--;

			    	//disable things
			    	$('#second-quantity').attr({'disabled':'disabled'});

					//if no checkboxes are checked
				  	if(checkcount < 1){

					  	//disable submit button
				  		//$('#store-submit').attr({'disabled':'disabled'});
						
					}
				}
				
			}); //end $('#second-checkbo...change..

		}); //end $(document).ready...