www.webdeveloper.com
Results 1 to 5 of 5

Thread: Need to create category tree using select tag

  1. #1
    Join Date
    Dec 2013
    Posts
    1

    Need to create category tree using select tag

    Hi all, I'm a beginner in js
    I need to create a tree. What do I mean under "a tree"? There have to be some <select>s next to each other. For example, if I have [Electronics->PCs->AMD] here have to be 3 <select>s (first select is general category list, second select is sub-categories of first select and ect. I hope you understand).
    And I have a code
    Code:
    Category<br>
    <script>
    var cntOfLevels = 0;
    function addCat(id)
    {
    if(id == -1) $("#category").html("");
    else
    	{
    		$.get( "/getCategory.php?id="+id, function(html)
    			{
    				if(html!="0") $("#catList").html(html);
    				else 
    				{
    					$("#catList").html("");
    					document.getElementById("category").value = id;
    				}
    			}
    		);
    	}
    }
    </script>
    <?php
    $res = mysql_query("SELECT id,name FROM categories WHERE parent IS NULL");
    echo "<select onchange=\"addCat(this.value);\">";
    echo "<option value=\"-1\">Choose item</option>";
    while($i = mysql_fetch_assoc($res)) echo "<option value=\"$i[id]\">$i[name]</option>";
    echo "</select>";
    ?>
    <span id="catList"></span>
    <input type="hidden" name="category" id="category">
    But this code works only with two categories, but I may have 3-4. Have you an idea to do it?

  2. #2
    Join Date
    Nov 2012
    Location
    Jakarta
    Posts
    42
    Check this link on how to dynamically create your select:
    http://stackoverflow.com/questions/7...-in-javascript

  3. #3
    Join Date
    Mar 2007
    Location
    localhost
    Posts
    2,342
    How can I put this so you can understand...

    JQuery IS NOT JavaScript, it is a framework tool just like mootools, prototype, et al.

    if you want to use JavaScript that all well and good, I suggest that you start at the beginning and learn the difference between a site helper tool like JQuery and what JavaScript is.
    Yes, I know I'm about as subtle as being hit by a bus..(\\.\ Aug08)
    Yep... I say it like I see it, even if it is like a baseball bat in the nutz... (\\.\ Aug08)
    I want to leave this world the same way I came into it, Screaming, Incontinent & No memory!
    I laughed that hard I burst my colostomy bag... (\\.\ May03)
    Life for some is like a car accident... Mine is like a motorway pile up...

    Problems with Vista? :: Getting Cryptic wid it. :: The 'C' word! :: Whois?

  4. #4
    Join Date
    Dec 2005
    Location
    FL
    Posts
    7,373

    Lightbulb

    One 3-level possibility...

    Code:
    <html>
    <head>
    <title> 3-level Drop Down</title>
    <script type="text/javascript">
    // From: http://www.codingforums.com/showthread.php?t=202456
    // and: http://www.codingforums.com/showthread.php?t=169465
    
    var categories = [];
      categories["startList"] = ["Apparel","Books"];                   // Level 1
      
        categories["Apparel"] = ["Men","Women"];                         // Level 2
          categories["Men"] = ["Shirts","Ties","Belts"];                   // Level 3
          categories["Women"] = ["Blouses","Skirts","Scarves"];
    	  
        categories["Books"] = ["Biography","Fiction","Nonfiction"];      // Level 2
          categories["Biography"] = ["Contemporay","Historical","Other"];  // Level 3
          categories["Fiction"] = ["Science","Romance"];
          categories["Nonfiction"] = ["How-To","Travel","Cookbooks"];
    
    var nLists = 3; // number of lists in the set
    
    function fillSelect(currCat,currList){
      var step = Number(currList.name.replace(/\D/g,""));
      for (i=step; i<nLists+1; i++) {
        document.forms[0]['List'+i].length = 1;
        document.forms[0]['List'+i].selectedIndex = 0;
      }
      var nCat = categories[currCat];
      for (each in nCat) 	{
        var nOption = document.createElement('option'); 
        var nData = document.createTextNode(nCat[each]); 
        nOption.setAttribute('value',nCat[each]); 
        nOption.appendChild(nData); 
        currList.appendChild(nOption); 
      } 
    }
    
    function getValues() { 
      var str = '';
      str += document.getElementById('List1').value+'\n';
      str += document.getElementById('List2').value+'\n';
      str += document.getElementById('List3').value+'\n';
      alert(str); 
    }
    
    function init() { fillSelect('startList',document.forms[0]['List1']); }
    
    navigator.appName == "Microsoft Internet Explorer"
    		   ? attachEvent('onload', init, false) 
    		   : addEventListener('load', init, false);	
    
    </script>
    </head>
    <body>
    <form action="" onsubmit="return false">
    <select name='List1' id="List1" onchange="fillSelect(this.value,this.form['List2'])">
    <option selected>Make a selection</option>
    </select> &nbsp;
    <select name='List2' id="List2" onchange="fillSelect(this.value,this.form['List3'])">
    <option selected>Make a selection</option>
    </select> &nbsp;
    <select name='List3' id="List3" onchange="getValues()">
    <option selected >Make a selection</option>
    </select> &nbsp;
    <button onclick="getValues()">Show selections</button>
    </form>
    </body>
    </html>

  5. #5
    Join Date
    Dec 2005
    Location
    FL
    Posts
    7,373

    Lightbulb

    Modified post #4 to show how a 1 to 4 (or more) level dropdown selection could be implemented...
    Code:
    <html>
    <head>
    <title> 1- to 4-level Drop Down</title>
    <style type="text/css">
    .DDlist { display:none; }
    </style>
    
    <script type="text/javascript">
    // From: http://www.codingforums.com/showthread.php?t=202456
    // and: http://www.codingforums.com/showthread.php?t=169465
    // Modified for 1 to 4 (+) level drop down selections
    
    var categories = [];
      categories["startList"] = ["Apparel","Books",'Radio','True','False'];        // Level 1  (True|False is 1 level only)
      
        categories["Apparel"] = ["Men","Women"];                         // Level 2
          categories["Men"] = ["Shirts","Ties","Belts"];                    // Level 3
            categories['Shirts'] = ['Tux','Button-down','Polo',"T's"]         //  Level 4
            categories['Ties'] = ['Silk','String','Bow']                      //  Level 4
            categories['Belts'] = ['Leather','Cloth']                         //  Level 4
    
          categories["Women"] = ["Blouses","Skirts","Scarves"];             // Level 3
            categories["Blouses"] = ["Silk","Cotton","Polyester"];             // Level 4 only
            categories["Skirts"] = ["Full","Pleated"];                         // Level 4 only
            categories["Scarves"] = ["Head","Neck","Waist"];                   // Level 4 only
    	  
        categories["Books"] = ["Biography","Fiction","Nonfiction"];      // Level 2
          categories["Biography"] = ["Contemporary","Historical","Other"];  // Level 3 only
          categories["Fiction"] = ["Science","Romance"];                    // Level 3 only
          categories["Nonfiction"] = ["How-To","Travel","Cookbooks"];       // Level 3 only
    
        categories['Radio'] = ['AM','FM','HD'];                          // Level 2 only
    
    var nLists = 4; // number of lists in the set
    
    function fillSelect(currCat,currList){
      var step = Number(currList.name.replace(/\D/g,""));
      for (i=step; i<nLists+1; i++) {
        document.forms[0]['List'+i].length = 1;
        document.forms[0]['List'+i].selectedIndex = 0;
        document.getElementById('List'+i).style.display = 'none';
      }
      var nCat = categories[currCat];
      if (nCat != undefined) { 
        document.getElementById('List'+step).style.display = 'inline';
        for (each in nCat) 	{
          var nOption = document.createElement('option'); 
          var nData = document.createTextNode(nCat[each]); 
          nOption.setAttribute('value',nCat[each]); 
          nOption.appendChild(nData); 
          currList.appendChild(nOption); 
        }
      } 
    }
    
    function getValues() { 
      var str = '';
      str += document.getElementById('List1').value+'\n';
      for (var i=2; i<=nLists; i++) {
        if (document.getElementById('List'+i).selectedIndex != 0) {
          str += document.getElementById('List'+i).value+'\n'; }
      }
      alert(str); 
    }
    
    function init() { fillSelect('startList',document.forms[0]['List1']); }
    
    navigator.appName == "Microsoft Internet Explorer"
       ? attachEvent('onload', init, false) 
    		   : addEventListener('load', init, false);	
    
    </script>
    </head>
    <body>
    <form action="" onsubmit="return false">
    
    <select name='List1' id="List1" onchange="fillSelect(this.value,this.form['List2'])">
    <option selected>Make a selection</option>
    </select> &nbsp;
    
    <select name='List2' id="List2" onchange="fillSelect(this.value,this.form['List3'])" class="DDlist">
    <option selected>Make a selection</option>
    </select> &nbsp;
    
    <select name='List3' id="List3" onchange="fillSelect(this.value,this.form['List4'])" class="DDlist">
    <option selected >Make a selection</option>
    </select> &nbsp;
    
    <select name='List4' id="List4" class="DDlist">
    <option selected >Make a selection</option>
    </select> &nbsp;
    
    <!-- can add more levels if desired as "List5"+ -->
    <button onclick="getValues()">Show selections</button>
    </form>
    </body>
    </html>

Thread Information

Users Browsing this Thread

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

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