Dynamic Dropdown

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • divyac
    New Member
    • Aug 2008
    • 40

    Dynamic Dropdown

    Using javascript i have created dynamic fields in a form with an "add" button.If i press "add" button the fields get repeated.

    Now my problem is that,after entering the values in the form,the values in the dropdown box field gets refreshed if i press the "add" button.

    my requirement is that the "add" button should be pressed each time after entering the data before repeating the form.

    After entering all the required values for the required number of times the "Submit" button should be pressed which takes all the values to the database at once.

    The number of times the "add" button should be pressed will vary time to time.
  • RamananKalirajan
    Contributor
    • Mar 2008
    • 608

    #2
    Hi Divya, I was not able to follow ur requirement. can you please post ur code what u have tried so far. I cant clearly catch ur requirement. In a form you are dynamically populating some text field. when u fill up the text field ur drop down gets changed. i cant get this point clearly.

    Regards
    Ramanan Kalirajan

    Comment

    • divyac
      New Member
      • Aug 2008
      • 40

      #3
      [HTML]<html>
      <head>
      <script language="javas cript">
      function createTable(id, ctr)
      {
      var tbody = document.getEle mentById(id).ge tElementsByTagN ame("TBODY")[0];
      var i;
      for(i=1;i<=ctr; i++)
      {

      var row1td1=documen t.createElement ('TD');
      var row1td1sel=docu ment.createElem ent('select' );
      row1td1sel.setA ttribute('id',' PA'+i,'NAME','p refer ence_access');
      row1td1.appendC hild(row1td1sel );

      var subrow1_y=docum ent.createEleme nt('option');
      subrow1_y.inner HTML='Y';
      subrow1_y.value =1;

      var subrow1_n=docum ent.createEleme nt('option');
      subrow1_n.inner HTML='N';
      subrow1_n.value =2;

      row1td1sel.appe ndChild(subrow1 _y);
      row1td1sel.appe ndChild(subrow1 _n);




      var row1td2=documen t.createElement ('TD');
      var row1td2sel=docu ment.createElem ent('select' );
      row1td2sel.setA ttribute('id',' RA'+i,'NAME','r eques t_access');
      row1td2.appendC hild(row1td2sel );

      var subrow2_y=docum ent.createEleme nt('option');
      subrow2_y.inner HTML='Y';
      subrow2_y.value =1;

      var subrow2_n=docum ent.createEleme nt('option');
      subrow2_n.inner HTML='N';
      subrow2_n.value =2;
      row1td2sel.appe ndChild(subrow2 _y);
      row1td2sel.appe ndChild(subrow2 _n);




      var row1=document.c reateElement('T R');

      var row1td3=documen t.createElement ('TD');
      var row1td3_n=docum ent.createEleme nt('INPUT');
      row1td3.appendC hild(row1td3_n) ;
      row1td3_n.setAt tribute('TYPE', 'text');
      row1td3_n.setAt tribute('NAME', 'UID'+i);
      row1td3_n.setAt tribute('ID','U ID'+i);



      var row1td4=documen t.createElement ('TD');
      var row1td4_n=docum ent.createEleme nt('INPUT');
      row1td4.appendC hild(row1td4_n) ;
      row1td4_n.setAt tribute('TYPE', 'text');
      row1td4_n.setAt tribute('NAME', 'CID'+i);
      row1td4_n.setAt tribute('ID','C ID'+i);

      row1.appendChil d(row1td1);
      row1.appendChil d(row1td2);
      row1.appendChil d(row1td3);
      row1.appendChil d(row1td4);


      tbody.appendChi ld(row1);
      }
      }

      function addRowToTable()
      {
      var tbl = document.getEle mentById('t1hea d');
      var lastRow = tbl.rows.length ;
      // if there's no header row in the table, then iteration = lastRow + 1
      var iteration = lastRow;
      var row = tbl.insertRow(l astRow);

      // select cell
      var cell1 = row.insertCell( 0);
      var sel1 = document.create Element('select ');
      sel1.name = 'Categories';
      sel1.id='RA'+it eration;
      sel1.options[0] = new Option('Y', '0');
      sel1.options[1] = new Option('N', '1');
      cell1.appendChi ld(sel1);

      // select cell
      var cell2 = row.insertCell( 1);
      var sel2 = document.create Element('select ');
      sel2.name = 'preferences_ac cess';
      sel2.id='PA'+it eration;
      sel2.options[0] = new Option('Y', '0');
      sel2.options[1] = new Option('N', '1');
      cell2.appendChi ld(sel2);

      // left cell
      var cell3 = row.insertCell( 2);
      var textNode = document.create Element('input' );
      textNode.setAtt ribute('type',' text','name','t ext'+ iteration,'id', 'txt'+iteration );
      cell3.appendChi ld(textNode);

      // right cell
      var cell4 = row.insertCell( 3);
      var el = document.create Element('input' );
      el.type = 'text';
      el.name = 'text' + (iteration+1);
      el.id = 'txt' + (iteration+1);
      cell4.appendChi ld(el);
      }
      </script>
      <body bgcolor="#fffcd 0" onLoad=createTa ble('t1head',0) >
      <form >
      <table class="layout" border="4" align="center" width="100%" id=t1head>
      <tr>
      <td align="left"><b > Categories </b></td>
      <td align="left"><b > Items </b></td>
      <td align="left"><b > Quantity </b></td>
      <td align="left"><b > Price </b></td>
      </tr>
      </table>
      <table>
      <tr><td></td></tr><tr><td></td></tr>
      <tr><td></td></tr></tr><tr><td></td></tr>
      </tr><tr><td></td></tr><tr><td></td></tr>
      <tr><td></td></tr></tr><tr><td></td></tr>
      </table>
      <table class="layout" border="0" align="center" id=tabBtn>
      <tr>
      <td align="center" colspan="2">
      <input type="button" value="ADD" name="add" onClick="addRow ToTable()">
      </td>

      <td align="center" colspan="2">
      <input type="submit" value="SAVE" name="save">
      </td>


      <td align="center" colspan="2">
      <input type="button" value="CANCEL" name="cancel" onClick="histor y.go(0)">
      </td>
      </tr>
      </table>
      </form>
      </body>
      </html>
      [/HTML]
      The above code is taken from the same forum posted by u which is the required one for me..Now my problem is the two dropdown boxes in which i have used ajax..i cant incorporate it in ur above code...the code which i tried was:


      [CODE=javascript] function generateRow() {
      var d=document.getE lementById("div ");
      d.innerHTML+="C ategory : ";

      d.innerHTML+="< select name='Categorie s' id='Categories" + numLinesAdded + "' onChange='itemC ollect(this.val ue," + numLinesAdded + ")'><option value=''>------Select Category------</option><?php while($resultse t=mysql_fetch_a rray($category) ){?><option value='<?=$resu ltset['category_id'];?>'><?=$result set['Categories']; ?></option><?php }?></select>&nbsp;&n bsp;&nbsp;&nbsp ;&nbsp;&nbsp; ";

      d.innerHTML+="I tems : ";

      d.innerHTML+="< select id='itemList" + numLinesAdded + "'><option value=''>------Select an Item------</option></select>&nbsp;&n bsp;&nbsp;&nbsp ;&nbsp;&nbsp; ";

      d.innerHTML+="Q uantity : ";

      d.innerHTML+="< input type='text' maxlength='5' name='Quantity" + numLinesAdded + "' onkeypress='foc usNext(this)'>& nbsp;&nbsp;&nbs p;&nbsp;&nbsp;& nbsp;";

      d.innerHTML+="P rice : ";

      d.innerHTML+="< input type='text' name='Price" + numLinesAdded + "'><br><br> " ;
      numLinesAdded++ ;
      }
      [/CODE]The values for the dropdown are taken directly from the database through ajax...Is it possible to fulfill my requirement???? pls help me...



      The problem with my code is that whenever i click "submit",th e values in the dropdown gets refreshed and not saved which is rectified in ur code..
      Last edited by acoder; Aug 26 '08, 11:51 AM. Reason: Added [code] tags

      Comment

      • RamananKalirajan
        Contributor
        • Mar 2008
        • 608

        #4
        Why can't you go for DOM rather using innerHTML. This seems to be some what new for me. I will try to help you out. In your code

        [HTML]d.innerHTML+="< select name='Categorie s' id='Categories" + numLinesAdded + "' onChange='itemC ollect(this.val ue," + numLinesAdded + ")'><option value=''>------Select Category------</option><?php while($resultse t=mysql_fetch_a rray($category) ){?><option value='<?=$resu ltset['category_id'];?>'><?=$result set['Categories']; ?></option><?php }?></select>&nbsp;&n bsp;&nbsp;&nbsp ;&nbsp;&nbsp; ";[/HTML]

        instead of using this just give some static data in d.innerHTML. Like this

        [HTML]d.innerHTML+= <select name="Categorie s" id="Categories " onChange="itemC ollect(this)">< option value="1">Y</option> <option value="0">N</option></select>[/HTML]

        and try running your code. Instead of retrieving the values from the DB just hard code it and test it out. if it works, you have to use DOM rather using innerHTML. just try it and post back the result i will try to help u out

        Regards
        Ramanan Kalirajan

        Comment

        • divyac
          New Member
          • Aug 2008
          • 40

          #5
          Originally posted by RamananKaliraja n
          Why can't you go for DOM rather using innerHTML. This seems to be some what new for me. I will try to help you out. In your code

          [HTML]d.innerHTML+="< select name='Categorie s' id='Categories" + numLinesAdded + "' onChange='itemC ollect(this.val ue," + numLinesAdded + ")'><option value=''>------Select Category------</option><?php while($resultse t=mysql_fetch_a rray($category) ){?><option value='<?=$resu ltset['category_id'];?>'><?=$result set['Categories']; ?></option><?php }?></select>&nbsp;&n bsp;&nbsp;&nbsp ;&nbsp;&nbsp; ";[/HTML]

          instead of using this just give some static data in d.innerHTML. Like this

          [HTML]d.innerHTML+= <select name="Categorie s" id="Categories " onChange="itemC ollect(this)">< option value="1">Y</option> <option value="0">N</option></select>[/HTML]

          and try running your code. Instead of retrieving the values from the DB just hard code it and test it out. if it works, you have to use DOM rather using innerHTML. just try it and post back the result i will try to help u out

          Regards
          Ramanan Kalirajan


          No Ramanan,
          Each and every change in the project deals with the database.The contents in the dropdown are not static.It will increase or decrease day by day...so the values have to be retrieved from the database...i have to replace that "Y" and "N" with my data from the database...so i have used that technique..No other go....Thanks for your help.dont put much effort...i ll try it out myself.......

          Comment

          • RamananKalirajan
            Contributor
            • Mar 2008
            • 608

            #6
            Wether you are getting the DB values getting loaded in the Select. Your problem is when you submit the data you are not getting the selected value. Instead the select gets refreshed itself. You want the Selected value also to be saved/submitted when the form is submitted

            Regards
            Ramanan Kalirajan

            Comment

            • divyac
              New Member
              • Aug 2008
              • 40

              #7
              Yes exactly but now i ve come out with a new one..I am getting what i am expecting but i could not submit the values into the database...the javasript function is:


              Code:
                <script>
                var numLinesAdded = 0;
                var i=0;
               
              
              	function generateRow() {
              	
              	var placeHolder=document.getElementById('appendElem');
              	var placeHolderDiv=document.createElement('div');
              	var Category=document.createElement('select');
              	var Item=document.createElement('select');
              	var itemQuantity=document.createElement('input');
              	var itemPrice=document.createElement('input');
              	var itemControl='itemList' + i;
              	
              			Category.setAttribute('id','catList','NAME','catList[]');
              				Category.onchange=function(){itemCollect(this.value, itemControl);}
              			
              			Item.setAttribute('id',itemControl,'NAME','itemList[]');
              				Item.innerHTML="<option value=''>------Select an Item------</option>";
              						
              			itemQuantity.setAttribute('id','itemQty','NAME','itemQty[]');
              			
              			itemPrice.setAttribute('id','itemPrice','NAME','itemPrice[]');
              			
              					placeHolderDiv.appendChild(Category);
              					placeHolderDiv.appendChild(Item);
              					placeHolderDiv.appendChild(itemQuantity);
              					placeHolderDiv.appendChild(itemPrice);
              				
              				placeHolder.appendChild(placeHolderDiv);
              	
              		i++;
              	} 
              </script>


              and the ajax function is:



              [CODE=javascript]var xmlHTTP
              var itemXMLHTTP
              var categoryXMLHTTP
              var refId
              //function to select Items
              function itemCollect(str ,ref)
              //function itemCollect(str )
              {
              refId=ref
              itemXMLHTTP = GetXmlHttpObjec t()
              if(itemXMLHTTP == null)
              {
              alert("XML-HTTP object was not Created")
              return;
              }
              var URL="items.php? c=" + str +"&randID=" + Math.random()
              itemXMLHTTP.onr eadystatechange = categoryChanged
              itemXMLHTTP.ope n("GET",URL,"tr ue")
              itemXMLHTTP.sen d(null)

              }
              //category list
              function categoryCollect ()
              {

              categoryXMLHTTP = GetXmlHttpObjec t()
              if(categoryXMLH TTP == null)
              {
              alert("XML-HTTP object was not Created")
              return;
              }
              var URL="categoryLi stCollection.ph p?randID=" + Math.random()
              categoryXMLHTTP .onreadystatech ange = listCategory
              categoryXMLHTTP .open("GET",URL ,"true")
              categoryXMLHTTP .send(null)

              }

              //lists the category
              function listCategory(){

              if(categoryXMLH TTP.readyState == 4){
              var categoryListing = document.getEle mentById('catLi st')
              categoryListing .innerHTML=cate goryXMLHTTP.res ponseText
              }

              }


              //calls this function on selectCategory onreadystatecha nge
              function categoryChanged ()
              {

              if(itemXMLHTTP. readyState == 4)
              {

              document.getEle mentById(refId) .innerHTML = itemXMLHTTP.res ponseText
              }

              }



              //function to create XMLHTTP object
              function GetXmlHttpObjec t()
              {
              var xmlHttp = null
              try
              {
              // Firefox, Opera 8.0+, Safari
              xmlHttp = new XMLHttpRequest( )
              }
              catch (e)
              {
              // Internet Explorer
              try
              {
              xmlHttp = new ActiveXObject(" Msxml2.XMLHTTP" )
              }
              catch (e)
              {
              try
              {
              xmlHttp = new ActiveXObject(" Microsoft.XMLHT TP")
              }
              catch (e)
              {
              alert("Your browser does not support AJAX!")
              }
              }
              }
              return xmlHttp
              }[/CODE]

              Here,items.php and categoryListCol lection.php are the files from where the values are taken from the database for the dropdown boxes...
              can u get me....can u understand what i am expecting...
              Last edited by acoder; Aug 26 '08, 11:53 AM. Reason: Added [code] tags

              Comment

              • RamananKalirajan
                Contributor
                • Mar 2008
                • 608

                #8
                Hi, I am really happy that you over come ur previous problem. Now you are not able to save/submit the values in the DB. If yes means, can u post me the code how u are doing it


                Regards
                Ramanan Kalirajan

                Comment

                • divyac
                  New Member
                  • Aug 2008
                  • 40

                  #9
                  Originally posted by RamananKaliraja n
                  Hi, I am really happy that you over come ur previous problem. Now you are not able to save/submit the values in the DB. If yes means, can u post me the code how u are doing it


                  Regards
                  Ramanan Kalirajan
                  sorry for the delay in reply ramanan.i was on leave for the past 2 days....i ll send u my total code...today i am getting problem with foreach statement...and the appended values are not getting submitted...pls help me...

                  [HTML]<?php
                  include "connection.php ";
                  session_start() ;
                  $select= mysql_query("se lect * from master_items");
                  $category = mysql_query("se lect * from master_category ");
                  $supplier=mysql _query("select * from master_supplier s");

                  if(isset($_GET['submit']))
                  {
                  $result=mysql_q uery("select * from master_expenses where Item_id='$_GET[Items]'");
                  $resultset=mysq l_fetch_array($ result);
                  $item =mysql_query("s elect * from master_items where Item_id='$_GET[Items]'");
                  $items=mysql_fe tch_array($item );

                  $current_Stock= $items['stock'];
                  $avgPrice=$item s['avgPrice'];

                  $catList = $_GET['Categories'];
                  $itemControl= $_GET['itemList'];
                  $itemQty = $_GET['Quantity'];
                  $itemPrice = $_GET['Price'];

                  foreach($catLis t as $newQty)
                  {
                  $closing_Stock= $current_Stock + $itemQty;
                  $averagePrice= (float) ((($avgPrice*$c urrent_Stock) + ($itemQty * $itemPrice)) / $closing_Stock );
                  $quantity=$item Qty;
                  $amount=$quanti ty*$itemPrice;

                  $insert=mysql_q uery("INSERT INTO master_expenses (Date,
                  category_id,
                  Item_id,
                  transaction,
                  Quantity,
                  Price,
                  Total,
                  supplier_Name,
                  invoice_Number,
                  closing_Stock,
                  Average,
                  preStock)
                  VALUES(curdate( ),
                  '$_GET[Categories]',
                  '$_GET[Items]',
                  '$_GET[transaction]',
                  '$quantity',
                  '$itemPrice',
                  '$amount',
                  '$_GET[supplier_Name]',
                  '$_GET[invoice_Number]',
                  '$closing_Stock ',
                  '$averagePrice' ,
                  '$current_Stock ')") or die(mysql_error ());

                  $update=mysql_q uery("update master_items set stock='$closing _Stock', avgPrice= $averagePrice where Item_id='$_GET[Items]'");
                  header('locatio n:inward.php');
                  }
                  }
                  ?>

                  <html>
                  <head>
                  <script language="javas cript" src="deajax.js" ></script>

                  <script>
                  var numLinesAdded = 0;
                  var i=0;

                  function generateRow() {

                  var placeHolder=doc ument.getElemen tById('appendEl em');
                  var placeHolderDiv= document.create Element('div');
                  var Categories=docu ment.createElem ent('select');
                  var itemList=docume nt.createElemen t('select');
                  var Quantity=docume nt.createElemen t('input');
                  var Price=document. createElement(' input');
                  var itemControl='it emList' + i;

                  Categories.setA ttribute('id',' catList','NAME' ,'Categories[]');

                  Categories.onch ange=function() {itemCollect(th is.value, itemControl);}

                  itemList.setAtt ribute('id',ite mControl,'NAME' ,'itemList[]');
                  itemList.innerH TML="<option value=''>------Select an Item------</option>";

                  Quantity.setAtt ribute('id','it emQty','NAME',' Quantity[]');

                  Price.setAttrib ute('id','itemP rice','NAME','P rice[]');

                  placeHolderDiv. appendChild(Cat egories);
                  placeHolderDiv. appendChild(ite mList);
                  placeHolderDiv. appendChild(Qua ntity);
                  placeHolderDiv. appendChild(Pri ce);

                  placeHolder.app endChild(placeH olderDiv);

                  i++;
                  }
                  </script>
                  </head>

                  <body >

                  <form method="get">
                  <h3>Inward Transactions</h3>
                  <div><b>Selec t a supplier:</b></div>
                  <div>
                  <select name="supplier_ Name" id="supplier_Na me">
                  <option value="">------Select a Supplier------</option>
                  <?php while($resultse t=mysql_fetch_a rray($supplier) ){?>
                  <option value="<? echo $resultset['supplier_id']; ?>"><? echo $resultset['supplier_Name']; ?>
                  </option>
                  <?php }?>
                  </select>
                  </div>
                  <br>
                  <div><b>Invoi ce Number:</b></div>
                  <div><input type="text" size="30" name="invoice_N umber" id="invoice_Num ber"/></div>
                  <br>
                  <div id="div"></div>
                  <br>
                  <div id='appendElem' ></div>
                  <input type="button" value="Add Product(s)" onClick="genera teRow(), categoryCollect ()"/>
                  <input type="submit" name="submit" id="submit">
                  </form>
                  </body>
                  </html>[/HTML]
                  Last edited by gits; Aug 29 '08, 08:05 AM. Reason: added code tags

                  Comment

                  • RamananKalirajan
                    Contributor
                    • Mar 2008
                    • 608

                    #10
                    After this line,
                    [HTML] placeHolder.app endChild(placeH olderDiv);[/HTML]
                    pls insert a line
                    [HTML]placeHolder.inn erHTML=placeHol der.innerHTML;[/HTML]

                    This is a silly code but it refreshes ur container. Just try it out and post it back in the forum.

                    [Note: I am not very good at PHP. May be Acoder can help u out]

                    Regards
                    Ramanan Kalirajan.

                    Comment

                    • acoder
                      Recognized Expert MVP
                      • Nov 2006
                      • 16032

                      #11
                      Firstly, test that your PHP code works as expected. If you have problems with your PHP code, ask in the PHP forum.

                      Comment

                      Working...