473,386 Members | 1,801 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,386 software developers and data experts.

Dynamic Dropdown

40
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.
Aug 26 '08 #1
10 1983
RamananKalirajan
608 512MB
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
Aug 26 '08 #2
divyac
40
[HTML]<html>
<head>
<script language="javascript">
function createTable(id,ctr)
{
var tbody = document.getElementById(id).getElementsByTagName(" TBODY")[0];
var i;
for(i=1;i<=ctr;i++)
{

var row1td1=document.createElement('TD');
var row1td1sel=document.createElement('select' );
row1td1sel.setAttribute('id','PA'+i,'NAME','prefer ence_access');
row1td1.appendChild(row1td1sel);

var subrow1_y=document.createElement('option');
subrow1_y.innerHTML='Y';
subrow1_y.value=1;

var subrow1_n=document.createElement('option');
subrow1_n.innerHTML='N';
subrow1_n.value=2;

row1td1sel.appendChild(subrow1_y);
row1td1sel.appendChild(subrow1_n);




var row1td2=document.createElement('TD');
var row1td2sel=document.createElement('select' );
row1td2sel.setAttribute('id','RA'+i,'NAME','reques t_access');
row1td2.appendChild(row1td2sel);

var subrow2_y=document.createElement('option');
subrow2_y.innerHTML='Y';
subrow2_y.value=1;

var subrow2_n=document.createElement('option');
subrow2_n.innerHTML='N';
subrow2_n.value=2;
row1td2sel.appendChild(subrow2_y);
row1td2sel.appendChild(subrow2_n);




var row1=document.createElement('TR');

var row1td3=document.createElement('TD');
var row1td3_n=document.createElement('INPUT');
row1td3.appendChild(row1td3_n);
row1td3_n.setAttribute('TYPE','text');
row1td3_n.setAttribute('NAME','UID'+i);
row1td3_n.setAttribute('ID','UID'+i);



var row1td4=document.createElement('TD');
var row1td4_n=document.createElement('INPUT');
row1td4.appendChild(row1td4_n);
row1td4_n.setAttribute('TYPE','text');
row1td4_n.setAttribute('NAME','CID'+i);
row1td4_n.setAttribute('ID','CID'+i);

row1.appendChild(row1td1);
row1.appendChild(row1td2);
row1.appendChild(row1td3);
row1.appendChild(row1td4);


tbody.appendChild(row1);
}
}

function addRowToTable()
{
var tbl = document.getElementById('t1head');
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(lastRow);

// select cell
var cell1 = row.insertCell(0);
var sel1 = document.createElement('select');
sel1.name = 'Categories';
sel1.id='RA'+iteration;
sel1.options[0] = new Option('Y', '0');
sel1.options[1] = new Option('N', '1');
cell1.appendChild(sel1);

// select cell
var cell2 = row.insertCell(1);
var sel2 = document.createElement('select');
sel2.name = 'preferences_access';
sel2.id='PA'+iteration;
sel2.options[0] = new Option('Y', '0');
sel2.options[1] = new Option('N', '1');
cell2.appendChild(sel2);

// left cell
var cell3 = row.insertCell(2);
var textNode = document.createElement('input');
textNode.setAttribute('type','text','name','text'+ iteration,'id','txt'+iteration);
cell3.appendChild(textNode);

// right cell
var cell4 = row.insertCell(3);
var el = document.createElement('input');
el.type = 'text';
el.name = 'text' + (iteration+1);
el.id = 'txt' + (iteration+1);
cell4.appendChild(el);
}
</script>
<body bgcolor="#fffcd0" onLoad=createTable('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="addRowToTable()">
</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="history.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:


Expand|Select|Wrap|Line Numbers
  1.     function generateRow() {
  2.     var d=document.getElementById("div");
  3.     d.innerHTML+="Category : ";
  4.  
  5.     d.innerHTML+="<select name='Categories' id='Categories" + numLinesAdded + "' onChange='itemCollect(this.value," + numLinesAdded + ")'><option value=''>------Select Category------</option><?php while($resultset=mysql_fetch_array($category)){?><option value='<?=$resultset['category_id'];?>'><?=$resultset['Categories']; ?></option><?php }?></select>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;";
  6.  
  7.     d.innerHTML+="Items : ";
  8.  
  9.     d.innerHTML+="<select id='itemList" + numLinesAdded + "'><option value=''>------Select an Item------</option></select>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;";
  10.  
  11.     d.innerHTML+="Quantity : ";
  12.  
  13.     d.innerHTML+="<input type='text' maxlength='5' name='Quantity" + numLinesAdded + "' onkeypress='focusNext(this)'>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;";
  14.  
  15.     d.innerHTML+="Price : ";
  16.  
  17.     d.innerHTML+="<input type='text' name='Price" + numLinesAdded + "'><br><br>" ;
  18.     numLinesAdded++; 
  19.     } 
  20.  
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",the values in the dropdown gets refreshed and not saved which is rectified in ur code..
Aug 26 '08 #3
RamananKalirajan
608 512MB
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='Categories' id='Categories" + numLinesAdded + "' onChange='itemCollect(this.value," + numLinesAdded + ")'><option value=''>------Select Category------</option><?php while($resultset=mysql_fetch_array($category)){?>< option value='<?=$resultset['category_id'];?>'><?=$resultset['Categories']; ?></option><?php }?></select>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;";[/HTML]

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

[HTML]d.innerHTML+= <select name="Categories" id="Categories" onChange="itemCollect(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
Aug 26 '08 #4
divyac
40
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='Categories' id='Categories" + numLinesAdded + "' onChange='itemCollect(this.value," + numLinesAdded + ")'><option value=''>------Select Category------</option><?php while($resultset=mysql_fetch_array($category)){?>< option value='<?=$resultset['category_id'];?>'><?=$resultset['Categories']; ?></option><?php }?></select>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;";[/HTML]

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

[HTML]d.innerHTML+= <select name="Categories" id="Categories" onChange="itemCollect(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.......
Aug 26 '08 #5
RamananKalirajan
608 512MB
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
Aug 26 '08 #6
divyac
40
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:


Expand|Select|Wrap|Line Numbers
  1.   <script>
  2.   var numLinesAdded = 0;
  3.   var i=0;
  4.  
  5.  
  6.     function generateRow() {
  7.  
  8.     var placeHolder=document.getElementById('appendElem');
  9.     var placeHolderDiv=document.createElement('div');
  10.     var Category=document.createElement('select');
  11.     var Item=document.createElement('select');
  12.     var itemQuantity=document.createElement('input');
  13.     var itemPrice=document.createElement('input');
  14.     var itemControl='itemList' + i;
  15.  
  16.             Category.setAttribute('id','catList','NAME','catList[]');
  17.                 Category.onchange=function(){itemCollect(this.value, itemControl);}
  18.  
  19.             Item.setAttribute('id',itemControl,'NAME','itemList[]');
  20.                 Item.innerHTML="<option value=''>------Select an Item------</option>";
  21.  
  22.             itemQuantity.setAttribute('id','itemQty','NAME','itemQty[]');
  23.  
  24.             itemPrice.setAttribute('id','itemPrice','NAME','itemPrice[]');
  25.  
  26.                     placeHolderDiv.appendChild(Category);
  27.                     placeHolderDiv.appendChild(Item);
  28.                     placeHolderDiv.appendChild(itemQuantity);
  29.                     placeHolderDiv.appendChild(itemPrice);
  30.  
  31.                 placeHolder.appendChild(placeHolderDiv);
  32.  
  33.         i++;
  34.     } 
  35. </script>  
  36.  


and the ajax function is:



Expand|Select|Wrap|Line Numbers
  1. var xmlHTTP
  2. var itemXMLHTTP
  3. var categoryXMLHTTP
  4. var refId
  5. //function to select Items
  6. function itemCollect(str,ref)
  7. //function itemCollect(str)
  8. {
  9.     refId=ref
  10.     itemXMLHTTP = GetXmlHttpObject()
  11.     if(itemXMLHTTP == null)
  12.     {
  13.         alert("XML-HTTP object was not Created")
  14.         return;
  15.     }
  16.         var URL="items.php?c=" + str +"&randID=" + Math.random()
  17.         itemXMLHTTP.onreadystatechange = categoryChanged
  18.         itemXMLHTTP.open("GET",URL,"true")
  19.         itemXMLHTTP.send(null)
  20.  
  21. }
  22. //category list
  23. function categoryCollect()
  24. {
  25.  
  26.     categoryXMLHTTP = GetXmlHttpObject()
  27.     if(categoryXMLHTTP == null)
  28.     {
  29.         alert("XML-HTTP object was not Created")
  30.         return;
  31.     }
  32.         var URL="categoryListCollection.php?randID=" + Math.random()
  33.         categoryXMLHTTP.onreadystatechange = listCategory
  34.         categoryXMLHTTP.open("GET",URL,"true")
  35.         categoryXMLHTTP.send(null)
  36.  
  37. }
  38.  
  39. //lists the category
  40. function listCategory(){
  41.  
  42.     if(categoryXMLHTTP.readyState == 4){
  43.         var categoryListing    = document.getElementById('catList')
  44.         categoryListing.innerHTML=categoryXMLHTTP.responseText
  45.     }
  46.  
  47. }
  48.  
  49.  
  50. //calls this function on selectCategory onreadystatechange
  51. function categoryChanged()
  52. {
  53.  
  54.     if(itemXMLHTTP.readyState == 4)
  55.     {
  56.  
  57.         document.getElementById(refId).innerHTML = itemXMLHTTP.responseText
  58.     }
  59.  
  60. }
  61.  
  62.  
  63.  
  64. //function to create XMLHTTP object
  65. function GetXmlHttpObject()
  66. {
  67.     var xmlHttp = null
  68.   try
  69.     {
  70.     // Firefox, Opera 8.0+, Safari
  71.     xmlHttp = new XMLHttpRequest()
  72.     }
  73.   catch (e)
  74.     {
  75.     // Internet Explorer
  76.     try
  77.       {
  78.       xmlHttp = new ActiveXObject("Msxml2.XMLHTTP")
  79.       }
  80.     catch (e)
  81.       {
  82.       try
  83.         {
  84.         xmlHttp = new ActiveXObject("Microsoft.XMLHTTP")
  85.         }
  86.       catch (e)
  87.         {
  88.         alert("Your browser does not support AJAX!")
  89.         }
  90.       }
  91.     }
  92.    return xmlHttp
  93. }
Here,items.php and categoryListCollection.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...
Aug 26 '08 #7
RamananKalirajan
608 512MB
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
Aug 26 '08 #8
divyac
40
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("select * from master_items");
$category = mysql_query("select * from master_category");
$supplier=mysql_query("select * from master_suppliers");

if(isset($_GET['submit']))
{
$result=mysql_query("select * from master_expenses where Item_id='$_GET[Items]'");
$resultset=mysql_fetch_array($result);
$item =mysql_query("select * from master_items where Item_id='$_GET[Items]'");
$items=mysql_fetch_array($item);

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

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

foreach($catList as $newQty)
{
$closing_Stock= $current_Stock + $itemQty;
$averagePrice= (float) ((($avgPrice*$current_Stock) + ($itemQty * $itemPrice)) / $closing_Stock );
$quantity=$itemQty;
$amount=$quantity*$itemPrice;

$insert=mysql_query("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_query("update master_items set stock='$closing_Stock', avgPrice= $averagePrice where Item_id='$_GET[Items]'");
header('location:inward.php');
}
}
?>

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

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

function generateRow() {

var placeHolder=document.getElementById('appendElem');
var placeHolderDiv=document.createElement('div');
var Categories=document.createElement('select');
var itemList=document.createElement('select');
var Quantity=document.createElement('input');
var Price=document.createElement('input');
var itemControl='itemList' + i;

Categories.setAttribute('id','catList','NAME','Cat egories[]');

Categories.onchange=function(){itemCollect(this.va lue, itemControl);}

itemList.setAttribute('id',itemControl,'NAME','ite mList[]');
itemList.innerHTML="<option value=''>------Select an Item------</option>";

Quantity.setAttribute('id','itemQty','NAME','Quant ity[]');

Price.setAttribute('id','itemPrice','NAME','Price[]');

placeHolderDiv.appendChild(Categories);
placeHolderDiv.appendChild(itemList);
placeHolderDiv.appendChild(Quantity);
placeHolderDiv.appendChild(Price);

placeHolder.appendChild(placeHolderDiv);

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

<body >

<form method="get">
<h3>Inward Transactions</h3>
<div><b>Select a supplier:</b></div>
<div>
<select name="supplier_Name" id="supplier_Name">
<option value="">------Select a Supplier------</option>
<?php while($resultset=mysql_fetch_array($supplier)){?>
<option value="<? echo $resultset['supplier_id']; ?>"><? echo $resultset['supplier_Name']; ?>
</option>
<?php }?>
</select>
</div>
<br>
<div><b>Invoice Number:</b></div>
<div><input type="text" size="30" name="invoice_Number" id="invoice_Number"/></div>
<br>
<div id="div"></div>
<br>
<div id='appendElem'></div>
<input type="button" value="Add Product(s)" onClick="generateRow(), categoryCollect()"/>
<input type="submit" name="submit" id="submit">
</form>
</body>
</html>[/HTML]
Aug 29 '08 #9
RamananKalirajan
608 512MB
After this line,
[HTML] placeHolder.appendChild(placeHolderDiv);[/HTML]
pls insert a line
[HTML]placeHolder.innerHTML=placeHolder.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.
Aug 29 '08 #10
acoder
16,027 Expert Mod 8TB
Firstly, test that your PHP code works as expected. If you have problems with your PHP code, ask in the PHP forum.
Aug 30 '08 #11

Sign in to post your reply or Sign up for a free account.

Similar topics

9
by: Bob Alston | last post by:
In 2002, "GrayJay" posted the following code: I did this in a jazz record catalogue to find composers - On a form "frmComposers" Create a text box - txtFindComposer, and add the following sub...
1
by: Shourie | last post by:
I've noticed that none of the child controls events are firing for the first time from the dynamic user control. Here is the event cycle. 1) MainPage_load 2) User control1_Load user clicks a...
1
by: russ | last post by:
Hi all, Here's a problem I'm having with a dynamic table. Following the guidelines here (http://www.codeproject.com/aspnet/dynamiccontrols.asp), which make perfect sense. The problem is that...
7
by: Jeff Uchtman | last post by:
I know I have done this but my mind is fried. I have a dynamic dropdown in a form. I need to pull both the dynamic dropdown's ID and name listed in the dropdown. Need a little help with grey...
0
by: cindy | last post by:
I have a dynamic datagrid. I have custom classes for the controls public class CreateEditItemTemplateDDL : ITemplate { DataTable dtBind; string strddlName; string strSelectedID; string...
9
by: Tarscher | last post by:
hi all, I have this seemingly simple problem. I have lost a lot of time on it though. When a user selects a value from a dropdownlist (static control) a dynamic control is generated. I have...
1
by: phpnewbie2007 | last post by:
I have 2 dynamic PHP dropdowns: The second dropdown populates from the first, depending on what is selected in the first. The page is showing issues in a department: The first dropdown...
1
by: MaryamSh | last post by:
Hi, I am creating a Dynamic Search in my application. I create a user control and in Page_load event I create a dynamic dropdownlist and 2 dynamic button (Add,Remove) By pressing Add button...
0
by: MaryamSh | last post by:
Create Dynamic Dropdownlist Controls and related event -------------------------------------------------------------------------------- Hi, I am creating a Dynamic Search in my application. I...
2
by: raamay | last post by:
I want to have a dynamic dropdown box whose entries would depend on the selection of an entry in the first dropdown box. BUT the second dropdown box should not reload, only the entries inside should...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: aa123db | last post by:
Variable and constants Use var or let for variables and const fror constants. Var foo ='bar'; Let foo ='bar';const baz ='bar'; Functions function $name$ ($parameters$) { } ...
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.