473,738 Members | 7,599 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

php and ajax dynamically created select box onchange event

11 New Member
i want to basically take some information for the product and let the user
enter the the material required to make this product

1.first page test.php
which takes product code and displays prodcut anme have used
ajax to avoid refreshing of page this works fine
2.now i have created one row with
checkbox|select box|text|text|t ext|text|
where in the select box values are fetched from table here also i have used ajax for getting the m_name automatically withput refreshi works fine (onchange event)
3.after that i have given a add rows button on which rows are added dynamically
with the same like static row i have added
now i wantto use the same function i have used for static select box for avoiding refreshing here how do i pass the onchange event here
and after pressing submit button the dynamic rows created disappears
can anybody help me wot is wrong with this

how do i pass dynamic elements values from the rows to the php along with the static row values
my code is as follows

Expand|Select|Wrap|Line Numbers
  1. test.php
  2.  
  3.  
  4. <?
  5.  
  6. include("../include/connection.php");
  7. if($_GET)
  8. {
  9. $p_cde=$_GET['p_cde'];
  10.  
  11. $cnt = count($_GET['m_cde'])+1;
  12.       for ($idx=0;$idx<=$cnt;$idx++) {
  13.           $m_cde= $_GET['m_cde'][$idx] ;
  14.           $m_name=$_GET['m_name'][$idx]; 
  15.           $um=$_GET['um'][$idx]; 
  16.           $qty=$_GET['qty'][$idx]; 
  17.           $overages=$_GET['overages'][$idx]; 
  18.      }
  19. }
  20. ?>
  21. <html>
  22. <head>
  23. <script src="test.js" ></script>
  24. </head>
  25. <body><form name="material" method="GET"> 
  26. <table id="tbl" border="1">
  27. <tr><td>
  28. <select name="p_cde" id="p_cde" onChange="showCode(this.value);">
  29.    <? 
  30.    $sqlpr = "select * from fgmaster order by p_cde ";
  31.     $db_query=$DB_site->query($sqlpr);
  32.     while($rspr=$DB_site->fetch_array($db_query)){
  33.                $combopr=$combopr."<option value='".$rspr['p_cde']."'";
  34.             if ($rspr['p_cde']==strtoupper($p_cde)){
  35.                 $combopr=$combopr."selected";
  36.                 }
  37.             $combopr=$combopr.">".$rspr['p_cde']."-".$rspr['p_name']."</option>\n";
  38.        }
  39.        echo $combopr;   
  40.  
  41.        ?> 
  42. </select>
  43. </td>
  44.  
  45. <td><input type="text" name="p_name" id="p_name" value=""></td>
  46. <td><input type="text" name="p_pckunit" id="p_pckunit" value=""></td></tr>
  47. <?
  48.     $sqlmaterial="select * from materialmaster order by m_cde";
  49.     $db_query_material=$DB_site->query($sqlmaterial);
  50.     while($rsmaterial=$DB_site->fetch_array($db_query_material)){
  51.                 $option_vals[]=$rsmaterial['m_cde']."-".$rsmaterial['m_name'];
  52. }
  53.     ?>
  54. <script>
  55. select_opt = new Array();
  56. <?
  57. for($i=0;$i<count($option_vals);$i++){
  58.     ?>
  59.         select_opt[<?= $i ?>] = '<?= $option_vals[$i] ?>';
  60.     <?
  61. }
  62. ?>
  63. </SCRIPT>
  64.  
  65. <tr bgcolor="#CCCCCC" bordercolor="#FFCCFF"> 
  66.       <th>&nbsp;&nbsp; </th>
  67.  
  68.       <th >Code</th>
  69.  
  70.       <th>Material description</th>
  71.  
  72.       <th>um</th>
  73.  
  74.       <th>qty</th>
  75.  
  76.       <th>overages</th>
  77.  
  78.  
  79.  
  80.     </tr>
  81.  
  82.  
  83.      <tr> 
  84.      <td><input type="checkbox" name="chk" id="chk"></td>
  85.         <td><select name='m_cde' id='m_cde' onChange='showmcode(this.value);'>
  86.            <? 
  87.            $sqlmr = "select * from materialmaster order by m_cde ";
  88.         $db_query_mr=$DB_site->query($sqlmr);
  89.         while($rsmr=$DB_site->fetch_array($db_query_mr)){
  90.                $combomr=$combomr."<option value='".$rsmr['m_cde']."'";
  91.             if ($rsmr['m_cde']==strtoupper($m_cde)){
  92.                 $combomr=$combomr."selected";
  93.                 }
  94.         $combomr=$combomr.">".$rsmr['m_cde']."-".$rsmr['m_name']."</option>\n";
  95.            }
  96.            echo $combomr;   
  97.         ?> 
  98.     </select></td>
  99.     </td><td><input type="text" name='m_name' id='m_name' value=""></td>
  100.     <td><input type="text" name='um' id='um' value=""></td>
  101.     <td><input type="text" name='qty' id='qty' value=""></td>
  102.     <td><input type="text" name='overages' id='overages' value=""></td>
  103.     </tr> 
  104.  
  105.     <tbody>
  106. </tbody>
  107. </table>
  108. <DIV>
  109. <input type ="button" value="Add Row" onclick="add_rows(document.getElementById('tbl'));">
  110. </div>
  111. <DIV><input type ="submit" value="Submit" name="myfields"></DIV>
  112. </form>
  113. </body>
  114. </html>
Expand|Select|Wrap|Line Numbers
  1. test.js
  2. ------------
  3. // JavaScript Document
  4. var xmlHttp;
  5. function showCode(str)
  6. xmlHttp=GetXmlHttpObject();   //Calls on the GetXmlHttpObject function to create an XMLHTTP object 
  7. if (xmlHttp==null)
  8.  {
  9.  alert ("Browser does not support HTTP Request");
  10.  return;
  11.  }
  12. var url="testget.php"; //Defines the url (filename) to send to the server 
  13. url=url+"?p_cde="+str;  //Adds a parameter (q) to the url with the content of the dropdown box 
  14. url=url+"&sid="+Math.random(); //Adds a random number to prevent the server from using a cached file 
  15. xmlHttp.onreadystatechange=stateChanged ; //Call stateChanged when a change is triggered 
  16. xmlHttp.open("GET",url,true);  //Opens the XMLHTTP object with the given url. 
  17. xmlHttp.send(null);                //Sends an HTTP request to the server 
  18. alert(url);
  19. }
  20. function showmcode(str)
  21. xmlHttp=GetXmlHttpObject();   //Calls on the GetXmlHttpObject function to create an XMLHTTP object 
  22. alert(str);
  23. if (xmlHttp==null)
  24.  {
  25.  alert ("Browser does not support HTTP Request");
  26.  return;
  27.  }
  28. var url="testget.php"; //Defines the url (filename) to send to the server 
  29. url=url+"?m_cde="+str;  //Adds a parameter (q) to the url with the content of the dropdown box 
  30. url=url+"&sid="+Math.random(); //Adds a random number to prevent the server from using a cached file 
  31. xmlHttp.onreadystatechange=stateChanged1 ; //Call stateChanged when a change is triggered 
  32. xmlHttp.open("GET",url,true);  //Opens the XMLHTTP object with the given url. 
  33. xmlHttp.send(null);                //Sends an HTTP request to the server 
  34. alert(url);
  35. }
  36. function stateChanged() 
  37. if (xmlHttp.readyState==4 || xmlHttp.readyState=="complete")
  38.  { 
  39.  
  40.    var ar=xmlHttp.responseText.split("|");
  41.  
  42.    document.getElementById("p_name").value=ar[0] ;
  43.    document.getElementById("p_pckunit").value=ar[1] ;
  44.  
  45.  
  46.  } 
  47. }
  48.  
  49. function stateChanged1() 
  50. if (xmlHttp.readyState==4 || xmlHttp.readyState=="complete")
  51.  { 
  52.    var ar=xmlHttp.responseText.split("|");
  53.    document.getElementById("m_name").value=ar[0] ;
  54.    document.getElementById("um").value=ar[1] ;
  55.   } 
  56. }
  57. function GetXmlHttpObject()
  58. {
  59. var xmlHttp=null;
  60. try
  61.  {
  62.  // Firefox, Opera 8.0+, Safari
  63.  xmlHttp=new XMLHttpRequest();
  64.  }
  65. catch (e)
  66.  {
  67.  //Internet Explorer
  68.  try
  69.   {
  70.   xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");
  71.   }
  72.  catch (e)
  73.   {
  74.   xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
  75.   }
  76.  }
  77. return xmlHttp;
  78. }
  79.  
  80.  
  81.  
  82. //FUNCTION FOR DYNAMIC ROW
  83.  
  84. j=0;
  85. function add_rows(obj){
  86.  
  87.     //tabObj = document.createElement("table");
  88.     //tbodyObj = document.createElement("tbody");
  89.  
  90.     tabCols = new init_table();
  91.     trObj = document.createElement("tr")
  92.     col_names = new Array("chk","m_cde","m_name","um","qty","overages"); 
  93.     for(i=0;i<tabCols.length;i++){
  94.         tdObj = document.createElement("td");
  95.         /*
  96.          if(create_object(tabCols[i])=="select")
  97.          {
  98.          mselect=create_object(tabCols[i],col_names[i]+'['+j+']')
  99.          mselect.onChange=showmcode(col_names[i]+'['+j+']');
  100.          tdObj.appendChild(mselect));
  101.          }*/
  102.  
  103.         tdObj.appendChild(create_object(tabCols[i],col_names[i]+'['+j+']'));
  104.  
  105.         //added on 04/09/2007 for onchage event on select box
  106. /*        if(tabCols[i]=="select"){
  107.         alert("hi");
  108.             col_names[i]+'['+j+']'="fieldevent('"+fieldname+"')";
  109.             var showmcode=new Function(col_names[i]+'['+j+']'.onchange);
  110.             if(col_names[i]+'['+j+']'.addEventListener){
  111.             col_names[i]+'['+j+']'.addEventListener('change',showmcode,false);
  112.             else if(col_names[i]+'['+j+']'.attachEvent){
  113.             col_names[i]+'['+j+']'.attachEvent('onchange',showmcode);}
  114.             }
  115.         /* this is a sample
  116.         sfield.onchange = "fieldevent('" + fieldname + "')"; 
  117.             var onChangeHandler = new Function(sfield.onchange); 
  118.             if (sfield.addEventListener) { 
  119.             sfield.addEventListener('change', onChangeHandler, false ); 
  120.             } else if (sfield.attachEvent) { 
  121.             sfield.attachEvent('onchange', onChangeHandler); 
  122.             } 
  123.             */
  124.             trObj.appendChild(tdObj);
  125.  
  126.     }
  127.     obj.firstChild.appendChild(trObj);
  128.  
  129.  
  130. j++;
  131.  
  132. }
  133.  
  134. function fieldevent(fname){ 
  135.  
  136. alert (fname); 
  137.  
  138.  
  139.  
  140. function init_table(){
  141.     tableProp = new Array();
  142.  
  143.     tableProp[0] = "checkbox";
  144.     tableProp[1] = "select"; //m_cde
  145.     tableProp[2] = "text"; //m_name
  146.     tableProp[3] = "text"; //um
  147.     tableProp[4] = "text"; //qty
  148.     tableProp[5] = "text"; //overages    
  149.     //tableProp[6] = "checkbox";
  150.  
  151.     return tableProp;
  152. }
  153.  
  154. function create_object(objType,nm){
  155.     if(objType == 'select'){
  156.         return getSelectBoxDOM(select_opt,nm);
  157.     }    
  158.  
  159.     obj = document.createElement("input");
  160.     obj.setAttribute("type",objType);
  161.     obj.setAttribute("name",nm);
  162.  
  163.  
  164.     return obj; 
  165. }
  166.  
  167. function getSelectBoxDOM(options,nm) {
  168.             selectBox =document.createElement('select');
  169.            for (x=0; x < options.length; x++) {
  170.                 optionItem =document.createElement('option');
  171.                    optionItem.appendChild(document.createTextNode(options[x]));
  172.                 selectBox.appendChild(optionItem);
  173.  
  174.  
  175.             }
  176.             selectBox.setAttribute("name",nm);
  177.  
  178.  
  179.            return selectBox;
  180.  
  181. }


Expand|Select|Wrap|Line Numbers
  1. testget.php
  2. ----------------
  3.  
  4.  
  5. <?php
  6. if($_GET)
  7. {
  8.  
  9. $p_cde=$_GET['p_cde']; 
  10.  
  11.  
  12. $con = mysql_connect('localhost', 'localhost', '');  //PHP opens a connection to a MySQL server 
  13.  
  14. if (!$con)
  15.  {
  16.  die('Could not connect: ' . mysql_error());
  17.  }
  18. mysql_select_db("erpmfg", $con);
  19. $sql="select * from fgmaster where p_cde = '".$p_cde."'";
  20. $result = mysql_query($sql);
  21. while($row = mysql_fetch_array($result)){
  22. $p_name=$row['p_name'];
  23. $p_pckunit=$row['p_pckunit'];
  24. echo $p_name."|".$p_pckunit;
  25. }
  26. }
  27.  
  28. if ($_GET)
  29. {
  30.  
  31. $m_cde=$_GET['m_cde'];
  32.  
  33. $sqlmr="select * from materialmaster where m_cde = '".$m_cde."'";
  34. $result1 = mysql_query($sqlmr);
  35.  
  36. while($row = mysql_fetch_array($result1)){
  37. $m_name=$row['m_name'];
  38. $um=$row['um'];
  39.  
  40. echo $m_name."|".$um;
  41. }
  42.  
  43.  
  44. mysql_close($con);
  45. ?>
Sep 5 '07 #1
21 29817
dmjpro
2,476 Top Contributor
Please use Code tags then it will be easy to Solve your Problem.

Kind regards,
Dmjpro.
Sep 5 '07 #2
acoder
16,027 Recognized Expert Moderator MVP
Leena, welcome to TSDN!

Did you know that you can specify languages in the code tags, e.g. [code=javascript]...[/code.] (remove the dot).
Sep 5 '07 #3
acoder
16,027 Recognized Expert Moderator MVP
Give your dynamically created elements ids. For your select, add the onchange when you create the element.
Sep 5 '07 #4
Leena P
11 New Member
Expand|Select|Wrap|Line Numbers
  1. j=1;
  2. function add_rows(obj){
  3.  
  4.      tabCols = new init_table();
  5.      trObj = document.createElement("tr")
  6.      col_names = new Array("chk","m_cde","m_name","um","qty","overages"); 
  7.      for(i=0;i<tabCols.length;i++){
  8.         tdObj = document.createElement("td");
  9.         /*         if(create_object(tabCols[i])=="select")
  10.          {
  11.          mselect=create_object(tabCols[i],col_names[i]+'['+j+']')
  12.          mselect.onChange=showmcode(col_names[i]+'['+j+']');
  13.          tdObj.appendChild(mselect));
  14.          }*/
  15.  
  16.         tdObj.appendChild(create_object(tabCols[i],col_names[i]+'['+j+']'));


i was trying the above commented line in add_rows function while creating a select box using createElement function for onchange where am i going wrong
Sep 5 '07 #5
acoder
16,027 Recognized Expert Moderator MVP
i was trying the above commented line in add_rows function while creating a select box using createElement function for onchange where am i going wrong
Use onchange (lower case "c").
Sep 5 '07 #6
Leena P
11 New Member
i tried that but then my add rows button does not create new row some error
but if comment that part then it works
how to give onchage event when the select box is created

Expand|Select|Wrap|Line Numbers
  1. function getSelectBoxDOM(options,nm) {
  2.             selectBox =document.createElement('select');
  3.            for (x=0; x < options.length; x++) {
  4.                 optionItem =document.createElement('option');
  5.                    optionItem.appendChild(document.createTextNode(options[x]));
  6.                 selectBox.appendChild(optionItem);
  7.  
  8.  
  9.             }
  10.             selectBox.setAttribute("name",nm);
  11.             selectBox.setAttribute("id",nm);
  12. //after this say selectBox.onchange=showmcode(nm.value)........ ??????
  13. where nm is the name of the selectbox
  14.            return selectBox;
  15. }           
  16.  
i tried this bt giving error property not supported

thanks.
Sep 5 '07 #7
acoder
16,027 Recognized Expert Moderator MVP
Please use code tags when posting code. Thanks!

You need to assign a function object to the onchange, not the result of the function. See this article.

Try:
Expand|Select|Wrap|Line Numbers
  1. selectBox.onchange = function() {
  2.  showmcode(selectBox.value);
  3. }
Sep 5 '07 #8
Leena P
11 New Member
i tried that but then my add rows button does not create new row some error
but if comment that part then it works
how to give onchage event when the select box is created

Expand|Select|Wrap|Line Numbers
  1. function getSelectBoxDOM(options,nm) {
  2.             selectBox =document.createElement('select');
  3.            for (x=0; x < options.length; x++) {
  4.                 optionItem =document.createElement('option');
  5.                    optionItem.appendChild(document.createTextNode(options[x]));
  6.                 selectBox.appendChild(optionItem);
  7.  
  8.  
  9.             }
  10.             selectBox.setAttribute("name",nm);
  11.             selectBox.setAttribute("id",nm);
  12. //after this say selectBox.onchange=showmcode(nm.value)........ ??????
  13. where nm is the name of the selectbox
  14.            return selectBox;
  15. }           
  16.  
  17.  
i tried this bt giving error property not supported

thanks.
Sep 5 '07 #9
acoder
16,027 Recognized Expert Moderator MVP
Make sure you use code tags. This is the final friendly request. The last post seems like a repeat of your previous comment.
Sep 5 '07 #10

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

Similar topics

4
6136
by: Bart van Deenen | last post by:
Hi all I have a script where I dynamically create multiple inputs and selects from a script. The inputs and selects must have an associated onchange handler. I have the script working fine on Firefox, Safari and Konqueror, but the onchange event just doesn't fire on IE6. Firefox's javascript console shows no errors, and the IE script debugger shows nothing. onchange is not triggered.
4
1906
by: Stone Chen | last post by:
Hello, I have form that uses javascript createElement to add additional input fields to it. However, my validating script will not process new input fields because it can only find the named input boxes already on the page. Anyone has any thoughts on how to solve this, your advice is much appreciated. Thanks
2
4669
by: somaskarthic | last post by:
Hi In my php code , i dynamically created table rows on button click event. Each row contain 3 selectboxes, 7 checkboxes . On each click of these elements i need to submit the form and save the data to database. After each submit , i need to display the previous added details (with some checkboxes checked and some others unchecked ..) and one new row for next updation. Here i need to collect all values submitted in the php page. There i...
1
2469
by: AndiSmith | last post by:
Hi guys, I wondered if anyone could help me with this problem, or even shed some light on the direction I need to take to resolve it? I'm using .NET 2.0 (C# flavor) to build a large user-based website. I've created an AJAX based user control, which is dynamically placed on a page (once, or multiple times) if the user has the correct permissions to receive it. It contains two drop down lists - employee value and partner value; and a...
3
4322
by: nuchphasu | last post by:
Hi I have a problem on Dropdownlist that connect database and retrieve data by Ajax.I write javascript like this ------------------------------------------------------------------------- function ManageYear_onchange(machinetype) { var iManageYear=document.forms.ddlManageYear.selectedIndex; var vManageYear=document.forms.ddlManageYear.value;
4
4501
by: coby | last post by:
I have an application with a form that has two parts : A & B. A should be a static form while B shoudl be dynamically loaded via AJAX/PHP. Using a select box on part A, the onchange event calls an AJAX PHP script that generates PART B (in HTML) On positive AJAX reply, Part B's HTML is replaced by the returned HTML (using innerHTML) Works perfect on IE, but not on FF. On FF, the new form is properly displayed, but when trying to submit...
1
2881
by: bambr | last post by:
I'm using following code: function cloneRow(tBodyId, sourceRowId) { var obj = document.getElementById(tBodyId); if(obj.tagName != 'TBODY') { for(var i = 0; i < obj.childNodes.length; i++) { if(obj.childNodes.tagName == 'TBODY')
2
3172
by: shivendravikramsingh | last post by:
hi friends, i m using a ajax function for retrieving some values from a database table,and display the values in required field,my prob is that the ajax function i m using is working f9 once,but if i change something in php file using in ajax function.it not refreshed,means its shows the previous result it not get updated.i can't understand whats the prob.this is the code i m using: <? include("config.inc.php"); //error_reporting(0); ...
8
1484
by: sheldonlg | last post by:
I am still improving my AJAX and I ran into something that I'm not sure how to do. I will have a page called where I will have a dropdown list at the top and a large display at the bottom. The display depends upon what is currently selected in the dropdown. This is readily done via AJAX which is activated with an onchange in the dropdown list. The contents of the bottom half of the page are created in the php script which is sent back...
0
8969
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, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9335
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
9263
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
8210
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
6751
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
6053
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
4825
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
3279
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
2745
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

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.