Can I use an Array to make this shorter?

Discussion in 'JavaScript' started by eventps, Apr 9, 2010.

  1. #1
    I have a javascript that runs when the page loads and presently there is a copy of the script for each div that needs to be checked.
    function zero() {
    var babydivC =	document.getElementById("baby").value;
    if (babydivC != "0"){
    	document.getElementById("babydiv").style.display ="block";
    }
    else
    {
    	document.getElementById("babydiv").style.display ="none";
    }
    
    var onetwodivC =	document.getElementById("onetwo").value;
    if (onetwodivC != "0"){
    	document.getElementById("onetwodiv").style.display ="block";
    }
    else
    {
    	document.getElementById("onetwodiv").style.display ="none";
    }
    }
    Code (markup):
    I was hoping that I could extract the 'baby' and 'onetwo' and place those in an array which then justs gets concatenated with the 'div' and 'divC' and used as needed.

    Mike
     
    eventps, Apr 9, 2010 IP
  2. d_s

    d_s Peon

    Messages:
    22
    Likes Received:
    0
    Best Answers:
    0
    Trophy Points:
    0
    #2
    Hi,

    May be you can use the associative arrays for this purpose. This enables you to store the values as
    divid=> value.

    No need to use the div and divC concatenation operations.

    you may give this code a try

    
    var arr = new Array();
    
    function test() //initialize this during body tag onload if necessary, else skip this functionality.
    {
        arr['babydiv'] = 0;
        arr['onetwodiv'] =0;
    }
    
    function set() //this handles the checking of the values and setting display accordingly.
    {
        arr["babydiv"] = document.getElementById("babydiv").value;
        arr["onetwodiv"] = document.getElementById("onetwodiv").value;
        
        if(arr["babydiv"]==0)
        {
        document.getElementById("babydiv").style.display="none";
        }
        else
        {
            document.getElementById("babydiv").display="block";
        }
    //similarly, for onetwo div, this can be used.
    }
    
    Code (markup):
    regards
    d_s.

     
    d_s, Apr 9, 2010 IP