www.webdeveloper.com
Results 1 to 3 of 3

Thread: Can I make the javascript in this form more efficient?

  1. #1
    Join Date
    Feb 2011
    Posts
    2

    Can I make the javascript in this form more efficient?

    Hi all,

    I've been trying to build a form with dynamic checkboxes.

    I'd like to have a master 'select none' checkbox in a few form fields which has 2 key functions:-

    1) clearing all field boxes the user may have entered before opting to select none
    2) disabling all field options to make it impossible for the user to tick both 'none' and other options.

    This 'select none' checkbox should be ticked by default, so when the user unchecks it, the rest of the field options light up.


    I'm a complete novice but I have it working ok having stitched a few pieces of code I've found together, however I don't think it's very efficient.

    I have had to duplicate both bits of the javascript to make it work, changing only the function names in the <head> area ('Uncheck' and 'Uncheck2') and the class variables in the form in the <body> area ('fruit_child' and 'veg_child').

    As this form will have several more fields eventually, I'm looking for a better way to do this while maintaining the functionality. Ive read bits about object-orientated programming which may be what I'm looking for to make this more efficient, but I'm not sure how to implement it in this example.

    Can a more experienced coder please help?

    Kind thanks,
    Fleef

    HTML Code:
    <head>
    
    <SCRIPT LANGUAGE="JavaScript">
    // Check_ctr: clears all when 'none' box ticked -->
    function Uncheck(chk)
    {
    if(document.myform.Check_ctr.checked==true){
    for (i = 0; i < chk.length; i++)
    chk[i].checked = false ;
    }
    }
    
    // End -->
    </script>
    
    <SCRIPT LANGUAGE="JavaScript">
    // Check_ctr: clears all when 'none' box ticked -->
    function Uncheck2(chk_veg)
    {
    if(document.myform.Check_ctr_veg.checked==true){
    for (i = 0; i < chk_veg.length; i++)
    chk_veg[i].checked = false ;
    }
    }
    
    // End -->
    </script>
    
    </head>
    		
    		
    <body>
    
    <form name="myform"  method="post">
    
    <input type="checkbox" id="none_fruit" name="Check_ctr" value="yes"
    onClick="Uncheck(document.myform.fruit)" checked><b>None</b><br>
    <input type="checkbox" name="fruit" value="1" class="fruit_child" disabled="true">1<br>
    <input type="checkbox" name="fruit" value="2" class="fruit_child" disabled="true">2<br>
    <input type="checkbox" name="fruit" value="3" class="fruit_child" disabled="true">3<br>
    <input type="checkbox" name="fruit" value="4" class="fruit_child" disabled="true">4<br>
    <input type="checkbox" name="fruit" value="5" class="fruit_child" disabled="true">5<br>
    
    <script>
    // disables options when 'none' ticked -->
    
    $(function(){
      $("#none_fruit").click ( function() {
        
        if ( !$(this).is ( ":checked" ) )
        {
            $(".fruit_child").removeAttr ( "disabled" );
        }
        else
        {
       $(".fruit_child").attr ( "disabled" , true ); 
        }
      });
    });</script>
    
    
    
    
    <br><br><br>
    <input type="checkbox" id="none_veg" name="Check_ctr_veg" value="yes"
    onClick="Uncheck2(document.myform.veg)" checked><b>None</b><br>
    <input type="checkbox" name="veg" value="1" class="veg_child" disabled="true">1<br>
    <input type="checkbox" name="veg" value="2" class="veg_child" disabled="true">2<br>
    <input type="checkbox" name="veg" value="3" class="veg_child" disabled="true">3<br>
    <input type="checkbox" name="veg" value="4" class="veg_child" disabled="true">4<br>
    <input type="checkbox" name="veg" value="5" class="veg_child" disabled="true">5<br>
    
    <script>
    // disables options when 'none' ticked -->
    
    $(function(){
      $("#none_veg").click ( function() {
        
        if ( !$(this).is ( ":checked" ) )
        {
            $(".veg_child").removeAttr ( "disabled" );
        }
        else
        {
       $(".veg_child").attr ( "disabled" , true ); 
        }
      });
    });</script>
    
    
    </form>

  2. #2
    Join Date
    Mar 2010
    Posts
    2,803
    A few points:

    1) Since you are starting out I would recommend you learn the basics of javascript first before playing with jQuery. jQuery is a js framework and there is nothing you can in jQuery that you can't do with plain javascript. jQuery simply saves you writing lots of code (in most cases) because someone has already done it for you.

    If you rely solely on jQuery, I suspect you, like many others, will end up spending a lot of time in forums like this looking for help when you get stuck.

    2) Regarding recoding your functionality. I try to keep the javascript out of the html as much as possible and to make future code maintenance as easy as possible. With that in mind, the demo below allows you to put as many checkboxes as you like for the field options in each fieldset without having to touch the javascript.

    3) You can also change the names of the checkboxes in the future without having to touch the javascript.

    4) You can add as many groups (fieldsets) as you like to the form without having to touch the javascript

    5) If you send the form data to a php script, then the checkboxes with the same name must have [] at the end of the name (see demo)

    If you need more help, just post back

    Code:
    <html>
        <head>
            <script type="text/javascript">
                function toggleChkBoxes(obj){
                    var oGroupChkBoxes = getChkBoxes(obj);
                    switch (obj.checked){
                        case true:
                            for(i=0; i < oGroupChkBoxes.length; i++){
                                oGroupChkBoxes[i].checked = false;
                                oGroupChkBoxes[i].disabled = true;
                            }
                            break;
                        case false:
                            for(i=0; i < oGroupChkBoxes.length; i++){
                                oGroupChkBoxes[i].disabled = false;
                            }
                    }
                }
                window.onload=function(){
                    //assign the onclicks to the chkToggle class checkboxes
                    var oInputs = document.forms[0].getElementsByTagName('input');
                    for(i=0; i < oInputs.length; i++){
                        if(oInputs[i].className == 'chkToggle'){
                            oInputs[i].onclick=function(){
                                toggleChkBoxes(this);
                            }
                        }
                    }
                }
                function getChkBoxes(obj){
                    var oFldSet = obj.parentNode;
                    var oChkBoxes = oFldSet.getElementsByTagName('input');
                    var chkboxes = new Array();
                    for(i=0; i < oChkBoxes.length; i++){
                        if(oChkBoxes[i].type == 'checkbox' && oChkBoxes[i].name != obj.name){
                            chkboxes.push(oChkBoxes[i]);
                        }
                    }
                    return chkboxes;
                }
            </script>
        </head>
        <body>
            <form name="myform"  method="post" action="">
                <fieldset>
                    <input type="checkbox" id="none_fruit" name="Check_ctr" class="chkToggle" checked><b>None</b><br>
                    <input type="checkbox" name="fruit[]" value="1" class="fruit_child" disabled="true">1<br>
                    <input type="checkbox" name="fruit[]" value="2" class="fruit_child" disabled="true">2<br>
                    <input type="checkbox" name="fruit[]" value="3" class="fruit_child" disabled="true">3<br>
                    <input type="checkbox" name="fruit[]" value="4" class="fruit_child" disabled="true">4<br>
                    <input type="checkbox" name="fruit[]" value="5" class="fruit_child" disabled="true">5<br>
                </fieldset>
                <fieldset>
                    <input type="checkbox" id="none_veg" name="Check_ctr_veg" class="chkToggle" checked><b>None</b><br>
                    <input type="checkbox" name="veg[]" value="1" class="veg_child" disabled="true">1<br>
                    <input type="checkbox" name="veg[]" value="2" class="veg_child" disabled="true">2<br>
                    <input type="checkbox" name="veg[]" value="3" class="veg_child" disabled="true">3<br>
                    <input type="checkbox" name="veg[]" value="4" class="veg_child" disabled="true">4<br>
                    <input type="checkbox" name="veg[]" value="5" class="veg_child" disabled="true">5<br>
                </fieldset>
            </form>
        </body>
    </html>

  3. #3
    Join Date
    Feb 2011
    Posts
    2
    Dear Tirna,

    Thanks so much for putting the time in to respond so comprehensively to my post, very kind of you.

    I've finally had a chance to try your technique today and am delighted with your solution - definitely increases usability and flexibility. However there's a loss of functionality in the particular page I'm building. See below the wider accordian framework I'm trying to slot your code into.

    I've commented on where it stops working (anywhere beyond the closing tag of the first 'acc-content' div). No idea why this seems to be such a critical div!

    Thanks again for your help, very much appreciated.




    HTML Code:
    <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
            "http://www.w3.org/TR/html4/strict.dtd">
    		
    <html lang="en">
    
    <head>
    	<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
    	
    	<title>Javascript problem</title>
    
    	<script type="text/javascript">
                function toggleChkBoxes(obj){
                    var oGroupChkBoxes = getChkBoxes(obj);
                    switch (obj.checked){
                        case true:
                            for(i=0; i < oGroupChkBoxes.length; i++){
                                oGroupChkBoxes[i].checked = false;
                                oGroupChkBoxes[i].disabled = true;
                            }
                            break;
                        case false:
                            for(i=0; i < oGroupChkBoxes.length; i++){
                                oGroupChkBoxes[i].disabled = false;
                            }
                    }
                }
                window.onload=function(){
                    //assign the onclicks to the chkToggle class checkboxes
                    var oInputs = document.forms[0].getElementsByTagName('input');
                    for(i=0; i < oInputs.length; i++){
                        if(oInputs[i].className == 'chkToggle'){
                            oInputs[i].onclick=function(){
                                toggleChkBoxes(this);
                            }
                        }
                    }
                }
                function getChkBoxes(obj){
                    var oFldSet = obj.parentNode;
                    var oChkBoxes = oFldSet.getElementsByTagName('input');
                    var chkboxes = new Array();
                    for(i=0; i < oChkBoxes.length; i++){
                        if(oChkBoxes[i].type == 'checkbox' && oChkBoxes[i].name != obj.name){
                            chkboxes.push(oChkBoxes[i]);
                        }
                    }
                    return chkboxes;
                }
        </script>
    	
    </head>
    		
    		
    <body>
    
    <ul class="acc" id="acc">
    	
    		<li>
    		<h3>Your Details</h3>
    			<div class="acc-section">
    			
    			
    			<div class="acc-content">
    			
    			<form name="form1" method="post" action="contactformprocess.php">
    	
                <fieldset>
                    <input type="checkbox" id="none_fruit" name="Check_ctr" class="chkToggle" checked><b>None</b><br>
                    <input type="checkbox" name="fruit[]" value="1" class="fruit_child" disabled="true">1<br>
                    <input type="checkbox" name="fruit[]" value="2" class="fruit_child" disabled="true">2<br>
                    <input type="checkbox" name="fruit[]" value="3" class="fruit_child" disabled="true">3<br>
                    <input type="checkbox" name="fruit[]" value="4" class="fruit_child" disabled="true">4<br>
                    <input type="checkbox" name="fruit[]" value="5" class="fruit_child" disabled="true">5<br>
                </fieldset>
                <fieldset>
                    <input type="checkbox" id="none_veg" name="Check_ctr_veg" class="chkToggle" checked><b>None</b><br>
                    <input type="checkbox" name="veg[]" value="1" class="veg_child" disabled="true">1<br>
                    <input type="checkbox" name="veg[]" value="2" class="veg_child" disabled="true">2<br>
                    <input type="checkbox" name="veg[]" value="3" class="veg_child" disabled="true">3<br>
                    <input type="checkbox" name="veg[]" value="4" class="veg_child" disabled="true">4<br>
                    <input type="checkbox" name="veg[]" value="5" class="veg_child" disabled="true">5<br>
                </fieldset>
    					<!-- SCRIPT WORKS HERE-->
    	
    			</div><!-- ***** CHECKBOX SCRIPT DOESN'T WORK BELOW THIS DIV ****-->
    			
    			
    		</div>
    		
    	</li>
    	
    
    	<li>
    		<h3>SELECTIONS</h3>
    		
    		<div class="acc-section">
    			<div class="acc-content">
    				<ul class="acc" id="nested">
    					<li>
    						<h3>> Option set 1</h3>
    						<div class="acc-section">
    							<div class="acc-content">
    								
    							
    								<fieldset>  <!-- ****** SCRIPT DOES NOT WORK HERE ***** -->
    									<input type="checkbox" id="none_fruit" name="Check_ctr" class="chkToggle" checked><b>None</b><br>
    									<input type="checkbox" name="fruit[]" value="1" class="fruit_child" disabled="true">1<br>
    									<input type="checkbox" name="fruit[]" value="2" class="fruit_child" disabled="true">2<br>
    									<input type="checkbox" name="fruit[]" value="3" class="fruit_child" disabled="true">3<br>
    									<input type="checkbox" name="fruit[]" value="4" class="fruit_child" disabled="true">4<br>
    									<input type="checkbox" name="fruit[]" value="5" class="fruit_child" disabled="true">5<br>
    								</fieldset>
    								<fieldset>
    									<input type="checkbox" id="none_veg" name="Check_ctr_veg" class="chkToggle" checked><b>None</b><br>
    									<input type="checkbox" name="veg[]" value="1" class="veg_child" disabled="true">1<br>
    									<input type="checkbox" name="veg[]" value="2" class="veg_child" disabled="true">2<br>
    									<input type="checkbox" name="veg[]" value="3" class="veg_child" disabled="true">3<br>
    									<input type="checkbox" name="veg[]" value="4" class="veg_child" disabled="true">4<br>
    									<input type="checkbox" name="veg[]" value="5" class="veg_child" disabled="true">5<br>
    								</fieldset>
    		  						
    							</div>
    						</div>
    					</li>		
    				</ul>
    			</div>
    		</div>
    	</li>
    </ul>
    
    </form>
    
    
    <script type="text/javascript" src="script.js"></script>
    
    <script type="text/javascript">
    
    var parentAccordion=new TINY.accordion.slider("parentAccordion");
    parentAccordion.init("acc","h3",0,0);
    
    var nestedAccordion=new TINY.accordion.slider("nestedAccordion");
    nestedAccordion.init("nested","h3",1,-1,"acc-selected");
    
    </script>
    
    	
    
    
    </body>
    
    </html>

    and the script for the accordian incase required...

    Code:
    var TINY={};
    
    function T$(i){return document.getElementById(i)}
    function T$$(e,p){return p.getElementsByTagName(e)}
    
    TINY.accordion=function(){
    	function slider(n){this.n=n; this.a=[]}
    	slider.prototype.init=function(t,e,m,o,k){
    		var a=T$(t), i=s=0, n=a.childNodes, l=n.length; this.s=k||0; this.m=m||0;
    		for(i;i<l;i++){
    			var v=n[i];
    			if(v.nodeType!=3){
    				this.a[s]={}; this.a[s].h=h=T$$(e,v)[0]; this.a[s].c=c=T$$('div',v)[0]; h.onclick=new Function(this.n+'.pr(0,'+s+')');
    				if(o==s){h.className=this.s; c.style.height='auto'; c.d=1}else{c.style.height=0; c.d=-1} s++
    			}
    		}
    		this.l=s
    	};
    	slider.prototype.pr=function(f,d){
    		for(var i=0;i<this.l;i++){
    			var h=this.a[i].h, c=this.a[i].c, k=c.style.height; k=k=='auto'?1:parseInt(k); clearInterval(c.t);
    			if((k!=1&&c.d==-1)&&(f==1||i==d)){
    				c.style.height=''; c.m=c.offsetHeight; c.style.height=k+'px'; c.d=1; h.className=this.s; su(c,1)
    			}else if(k>0&&(f==-1||this.m||i==d)){
    				c.d=-1; h.className=''; su(c,-1)
    			}
    		}
    	};
    	function su(c){c.t=setInterval(function(){sl(c)},20)};
    	function sl(c){
    		var h=c.offsetHeight, d=c.d==1?c.m-h:h; c.style.height=h+(Math.ceil(d/5)*c.d)+'px';
    		c.style.opacity=h/c.m; c.style.filter='alpha(opacity='+h*100/c.m+')';
    		if((c.d==1&&h>=c.m)||(c.d!=1&&h==1)){if(c.d==1){c.style.height='auto'} clearInterval(c.t)}
    	};
    	return{slider:slider}
    }();

Thread Information

Users Browsing this Thread

There are currently 1 users browsing this thread. (0 members and 1 guests)

Tags for this Thread

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  
HTML5 Development Center



Recent Articles