www.webdeveloper.com
Results 1 to 7 of 7

Thread: How to select a column value based on another column value?

  1. #1
    Join Date
    Feb 2013
    Posts
    6

    How to select a column value based on another column value?

    Hi,

    I need to create a form with 2 columns (A & B), and when user select a value from the dropdown list in column A, all the values in column B that are related to Column A selection will show.

    Example:
    Column A -> Dropdown list with 5 values (vendor1,vendor2,vendor3,vendor4,vendor5)
    Column B-> By default will not show anything, once user select a vendor (eg. vendor1), all vendor1's products will show.

    Can someone please kindly advice? Thanks.

  2. #2
    Join Date
    Jan 2013
    Posts
    2
    Can't you just give each vendor a list of products, and use that list to fill the second colum once a vendor is selected?

  3. #3
    Join Date
    Dec 2005
    Location
    FL
    Posts
    7,259

    Lightbulb

    A quick search will render you a ton of examples of 1-, 2-, 3-level drop down lists.
    Consider this 2-level version (make modifications to your particular needs)
    Code:
    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
        "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
    <html xmlns="http://www.w3.org/1999/xhtml">
    <head>
    <title>2-level Drop Down Selection</title>
    <script type="text/javascript">
    // From: http://www.codingforums.com/showthread.php?t=223096
    
      var selOptions = [
    	  ['drink', 'water','milk','soda','wine','beer'],
    	  ['fruit', 'apple','orange','banana'],
          ['veggie','carrot','corn','potato'],
    	  ['meat',  'beef','chicken','lamb','pork','loaf'],
          ['cake',  'sponge','chocolate','tiramissu','mud'],
    	  ['coffee','black','cream','latte','cuban']
      ];
      function setSel2Options(obj){
        oSel2.options.length = 0;
    	if (obj.selectedIndex == 0) { return; }
    	for( i=0; i < selOptions.length; i++) {
          if (obj.value == selOptions[i][0]) {
            oSel2.options[oSel2.options.length] = new Option('Select a '+obj.value,'',false,false);
    		for (j=1; j < selOptions[i].length; j++) {  
              oSel2.options[oSel2.options.length] = new Option(selOptions[i][j],selOptions[i][j],false,false);
            }
            i = selOptions.length;
          }
        }
      }
      window.onload=function() {
        oSel1 = document.getElementById('sel1');
        oSel2 = document.getElementById('sel2');
        oSel1.options[oSel1.options.length] = new Option('Select an option','',false,false);
    	for (i=0; i < selOptions.length; i++) {
          oSel1.options[oSel1.options.length] = new Option(selOptions[i][0],selOptions[i][0], false,false);
        }
        oSel1.onchange=function(){setSel2Options(this);}
      }
      
      var savedInfo = [];
      for (i=0; i<selOptions.length; i++) { savedInfo[i] = ''; }
      function saveSelOptions() {
        oSel1 = document.getElementById('sel1');
        oSel2 = document.getElementById('sel2');
    	savedInfo[oSel1.selectedIndex] = oSel1.value + ':'+ oSel2.value;
    	var str = '';  	for (var i=0; i<savedInfo.length; i++) { str += savedInfo[i] +"\n"; }
    	document.getElementById('choices').innerHTML = str;
      }
      
    </script>
    </head>
    <body>
      <select id="sel1"></select>
      <select id="sel2" onchange="saveSelOptions()"></select>
      <button onclick="document.getElementById('choices').innerHTML=''">Clear</button>
      <div style="float:left"> Choices: 
       <pre id="choices"></pre>
      </div><br style="clear:both">
    </body>
    </html>

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

    Lightbulb

    Re-reading your original post, perhaps you are looking for something like this (?)...
    Code:
    <!DOCTYPE HTML>
    <html>
    <head>
    <title> Untitled </title>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
    <style type="text/css">
     .SBSselections { height:200px; width:300px; border:1px solid blue; }
     .SBSside { float:left; cursor:pointer; margin:0px 5px; padding:0px 15px; }
     #side1 a, #side2 a { text-decoration: none; }
    </style>
    
    </head>
    <body>
    <form action="" method="post" onsubmit="return false">
    <div id="SBSselections" class="SBSselections">
     <div id="side1" class="SBSside"></div>
     <div id="side2" class="SBSside"></div>
    </div>
    </form>
    
    <script type="text/javascript">
    var selOptions = [
        ['drink', 'water','milk','soda','wine','beer'],
        ['fruit', 'apple','orange','banana'],
        ['veggie','carrot','corn','potato'],
        ['meat',  'beef','chicken','lamb','pork','loaf'],
        ['cake',  'sponge','chocolate','tiramissu','mud'],
        ['coffee','black','cream','latte','cuban']
    ];
    
    function showPicks(info) {
    //  alert(info);
      var arr = info.split(':');
      alert(selOptions[arr[0]][0]+' : '+selOptions[arr[0]][arr[1]]);
      return false;
    }
    function subset(info) {
      var str = '<b>Options:</b><br>';
      for (var i=1; i<selOptions[info].length; i++) {
        tmp = "'"+info+':'+i+"'";
        str += '<a href="#" onclick="return showPicks('+tmp+')">'+selOptions[info][i]+'</a><br>';
      }
      document.getElementById('side2').innerHTML = str;
      return false;
    }
    window.onload = function() {
      var str = '<b>Selections:</b><br>';
      for (var i=0; i<selOptions.length; i++) {
        str += '<a href="#" onclick="return subset('+i+')">'+selOptions[i][0]+'</a><br>';
      }
      document.getElementById('side1').innerHTML = str;
      subset(0);
    }
    </script>
    </body>
    </html>

  5. #5
    Join Date
    Feb 2013
    Posts
    6
    Hi,

    Thanks for the reply. Acutally, I don't quite understand the coding but I tried to come out with the following codes. However, can anyone kindly advice how can I simplify it?

    Currently, if I have 2 vendors, I need to create 2 div id (1 contains all products from vendor 1) and (1 contains all products from vendor 2). However, if there are many vendors, I need to create alot div id which I do not want.

    I have created a database;
    1 Table (vendor) -> id(primary key), vendorname
    1 Table (product) -> id(primary key), productname, vendorid (foreign key)

    <script type="text/javascript">

    function hidefield(){
    document.getElementById('vendor1').style.display='none';
    document.getElementById('vendor2').style.display='none';
    }

    function showfield(name){
    if (name=='ABC'){
    document.getElementById('vendor1').style.display='block';
    }else{
    document.getElementById('vendor1').style.display='none';
    }

    if (name=='XYZ'){
    document.getElementById('vendor2').style.display='block';
    }else{
    document.getElementById('vendor2').style.display='none';
    }
    }

    </script>

    <html>
    <body onload="hidefield()">

    <td>
    <select name="vendor" onchange="showfield(this.options[this.selectedIndex].value)">
    <option value=""></option>
    <?php
    $result1=mysql_query("SELECT * FROM vendor");

    while ($row1=mysql_fetch_array($result1)){
    ?>
    <option value='<?php echo $row1["vendorname"]; ?>'><?php echo $row1["vendorname"]; ?></option>
    <?php } ?>
    </select>
    </td>

    <td>
    <div id="vendor1">
    <select name="product">
    <option value=""></option>
    <?php
    $result2=mysql_query("SELECT * FROM product WHERE vendorid=1");

    while ($row2=mysql_fetch_array($result2)){
    ?>
    <option value='<?php echo $row2["productname"]; ?>'><?php echo $row2["productname"]; ?></option>
    <?php } ?>
    </select>
    </div>

    <div id="vendor2">
    <select name="product">
    <option value=""></option>
    <?php
    $result2=mysql_query("SELECT * FROM product WHERE vendorid=2");

    while ($row2=mysql_fetch_array($result2)){
    ?>
    <option value='<?php echo $row2["productname"]; ?>'><?php echo $row2["productname"]; ?></option>
    <?php } ?>
    </select>
    </div>
    </td>
    </body>
    </html>



  6. #6
    Join Date
    Feb 2013
    Posts
    6
    Hi,

    I have managed to get the dependent drop-down list for my default 1st row. However, I have a "Add" button which user click will show another row. I have a problem as when user click the "Add" button, the codes below seems not working.

    Can someone please kindly help on this? Thanks.

    Code:
    <script type="text/javascript">
    
    function addInput(){
    	var tbl = document.getElementById('tblAddress');
    	var lastRow = tbl.rows.length;
    	var row = tbl.rows[lastRow-1].cloneNode(true);
    	tbl.tBodies[0].appendChild(row);
    	var txts = row.getElementsByTagName('input');
    	for(var i = 0; i < txts.length; i++){
    		if(txts[i].type == "text") {
    			txts[i].value = "";
    		}
    	}
    }
    
    function showfield(vname){
    
           var myForm = document.forms.myform;
           var selbox1=myForm.elements["vendor[]"];
           var selbox2=myForm.elements["product[]"];
    	
           selbox1.options.length = 1;
           selbox2.options.length = 0;
    	
           if (vname == "") { 
                  selbox2.options[selbox2.options.length] = new Option('','');   
           } 
    		
          <?php
                  $catresult=mysql_query("SELECT * FROM category");
                  while ($catrow=mysql_fetch_array($catresult)){
           ?>
                      if(vname==<?php echo $catrow["id"]; ?>){
    					
           <?php
                         $catid=$catrow["id"];
                         $vendresult=mysql_query("SELECT * FROM vendor WHERE categoryid='$catid'");
                         while ($vendrow=mysql_fetch_array($vendresult)){
           ?>
                                  selbox1.options[selbox1.options.length] = new Option('<?php echo $vendrow["vendorname"]; ?>','<?php echo $vendrow["id"]; ?>');
    							
          <?php
                          }					
           ?>
    				
    	      }
          <?php
    	   }
          ?>		
    }
    
    function showfield1(pname){
           var myForm = document.forms.myform;
           var selbox=myForm.elements["product[]"];
    	
           selbox.options.length = 1;
    	
           <?php
    	$vendresult=mysql_query("SELECT * FROM vendor");
    	while ($vendrow=mysql_fetch_array($vendresult)){
           ?>
    	     if(pname==<?php echo $vendrow["id"]; ?>){
    						
    	        <?php
    		    $vendid=$vendrow["id"];
    		    $prodresult=mysql_query("SELECT * FROM product WHERE vendorid='$vendid'");
    		     while ($prodrow=mysql_fetch_array($prodresult)){
    	        ?>
    			selbox.options[selbox.options.length] = new Option('<?php echo $prodrow["productname"]; ?>','<?php echo $prodrow["id"]; ?>');
    								
    	       <?php
    		      }
                         ?>
    					
    	         }
            <?php
    	      }
            ?>
    }
    </script>
    
    <html>
    <body>
    
    <form name="form" method="post" action="" id="myform" >
    <table border="1" id="tblAddress">	
    <tr>	
    <td>
         <select name="category[]" onchange="showfield(this.options[this.selectedIndex].value)">
    	<option value=""></option>
    	<?php					
                      $resultcategory = mysql_query("SELECT * FROM category");
                      while ($rowcategory = mysql_fetch_array($resultcategory)){
    	?>
                     <option value="<?php echo $rowcategory['id']; ?>"><?php echo $rowcategory['categoryname']; ?></option>
    	<?php
    	      }
    	?>
          </select>
    </td>
    
    <td>
             <select name="vendor[]" onchange="showfield1(this.options[this.selectedIndex].value)">
    	 <option value=""></option>
             </select>				
    </td>
    
    <td>
           <select name="product[]">
                 <option value=""></option>
           </select>				
    </td>
    </tr>
    </table>
    <input type="button" value="Add" onclick="addInput();">
    </form>
    
    </body>
    </html>

  7. #7
    Join Date
    Feb 2013
    Posts
    6
    Hi,

    I have created a triple dependent drop-downlist, however I have a problem if I click on the "Add" button function, there will be 2 errors.
    1. the onchange effect doesn't seems working.
    2. the default option value for vendor and product should be empty (no option value at all), however in all the rows there will be the same value if I select something in the dropdown list before I click the "Add" button.

    Can someone please kindly help on the below codes? Thanks.

    Code:
    <html>
    
    <head>
    	
    <script type="text/javascript">
    
    function addInput(){
    	var tbl = document.getElementById('tblAddress');
    	var lastRow = tbl.rows.length;
    	var row = tbl.rows[lastRow-1].cloneNode(true);
    	tbl.tBodies[0].appendChild(row);
    }
    
    function getParent(obj, parentType){
    	while (obj.parentNode){
    		if (obj.nodeName.toUpperCase()==parentType){
          			break;
        		}
       		obj=obj.parentNode;
      	}
      	return obj;
    }
    
    function removeInput(obj){
    	var row = getParent(obj, 'TR');
    	var tbl = getParent(row, 'TABLE');
      	if(tbl.rows.length > 2) { 
    		// one header row and one mandatory data row
        		// every row has a rowIndex attribute attached
        		// simply call the inbuilt deleteRow method by passing the row index
        		tbl.deleteRow(row.rowIndex);
      	}
    }
    
    function showfield(vname){
    
    var myForm = document.forms.myform;
    var selbox1=myForm.elements["vendor[]"];
    var selbox2=myForm.elements["product[]"];
    	
    	selbox1.options.length = 1;
    	selbox2.options.length = 0;
    	
    	if (vname == "") { 
    	    selbox2.options[selbox2.options.length] = new Option('','');   
    	} 
    				
    	if(vname=="Category 1"){
    		selbox1.options[selbox1.options.length] = new Option('C1_Vendor1','C1_Vendor1');
    		selbox1.options[selbox1.options.length] = new Option('C1_Vendor2','C1_Vendor2');	
    	}
    	
    	if(vname=="Category 2"){
    		selbox1.options[selbox1.options.length] = new Option('C2_Vendor1','C2_Vendor1');
    		selbox1.options[selbox1.options.length] = new Option('C2_Vendor2','C2_Vendor2');	
    	}			
    		
    }
    
    function showfield1(pname){
    	var myForm = document.forms.myform;
    	var selbox=myForm.elements["product[]"];
    	
    	selbox.options.length = 1;
    	
    	if(pname=="C1_Vendor1"){
    		selbox.options[selbox.options.length] = new Option('C1_V1_Product','C1_V1_Product');
    	}
    
    	if(pname=="C1_Vendor2"){
    		selbox.options[selbox.options.length] = new Option('C1_V2_Product','C1_V2_Product');
    	}
    	
    	if(pname=="C2_Vendor1"){
    		selbox.options[selbox.options.length] = new Option('C2_V1_Product','C2_V1_Product');
    	}
    
    	if(pname=="C2_Vendor2"){
    		selbox.options[selbox.options.length] = new Option('C2_V2_Product','C2_V2_Product');
    	}		
    }
    </script>
    </head>
    
    <body>
    
    
    <form name="form" method="post" action="" id="myform">			
    	
    		<table border="1" id="tblAddress">
    			<tr>				
    				<td align="center"><b>Category</b></td>
    				<td align="center"><b>Vendor</b></td>
    				<td align="center"><b>Product Description</b></td>
    				<td>&nbsp;</td>
    			</tr>
    		
    			<tr>
    				<td width="4%">
    					<select name="category[]" onchange="showfield(this.options[this.selectedIndex].value)">
    						<option value=""></option>
    						<option value="Category 1">Category 1</option>
    						<option value="Category 2">Category 2</option>
    					</select>
    				</td>
    				<td width="7%">
    					<select name="vendor[]" onchange="showfield1(this.options[this.selectedIndex].value)">
    						<option value=""></option>						
    					</select>				
    				</td>
    				<td width="15%">
    					<select name="product[]">
    						<option value=""></option>
    					</select>				
    				</td>
    				<td width="1%"><input type="button" value="Remove" onclick="removeInput(this);"></td>
    			</tr>
    		<table>
    	<br>
    
    <input type="button" value="Add" onclick="addInput();">
    	
    </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