Add/Remove rows from Table

Please support our JavaScript / DHTML / AJAX advertiser: PostgreSQL or MySQL? Compare and contrast the two most popular open source databases
Reply

Join Date: Jun 2009
Posts: 49
Reputation: sysel is an unknown quantity at this point 
Solved Threads: 3
sysel sysel is offline Offline
Light Poster

Re: Add/Remove rows from Table

 
0
  #11
Jul 1st, 2009
Hi again,

I do not want to argue what is an error and what does not. I tried to show some of my programing experiences.
You may see that a short function check() does the work of input validation very efficiently because it does not give a chance the user to write down a wrong character. It could be, of course, used also 'off line', but when it is called on each key up, you can write the other part of code more simply because you can relay on the input.

I did not understand the request for filled/empty input, but as you cleared it now the IF condition (line 53) have to be cosmetically corrected to emulate the XOR operator. (done).

It is very popular to give any DOM element the id attribute and then look for it by very complicated computed way. In most cases if the user click on some element, you can refer directly to the that/enclosing/neighbor/enclosed element by use of this object reference this this.parentNode this.nextSibling ....
Also you can get a collection of elements of the same TAG. Hence if you want to work with all <INPUT type="text">s on a single row, where the user clicked the button, simply collect those inputs:
JavaScript / DHTML / AJAX Syntax (Toggle Plain Text)
  1. AllInputsAtTheRow = this.parentNode.parentNode.getElementsByTagName('input')
and while walking through the collection, deal only with those which has the correct name, type, value or sequence number.

About the editing behavior – if one wants to edit a line, the text boxes must be enabled, hence, after the editing is finished, disable must take an effect. Thats why the button [ed] changes into the button [lock] and, in the same way the of ideas, only one row at the same moment can be edited, so other rows are disabled and the add/ed button, too. I forgot the possibility to delete the row at the moment of editing, but it was a minor repair :-) (done).

It is a good exercise to build the page completely by dynamic methodes createElement() appendNode() etc. But It must be pointed out, that browsers differs (not a bit) in interpreting such structure, but in the rendering the HTML they work more closely. So it was shown on the example. The 'prototype' row was completely written in HTML. They are some DOM elements which can be created more efficiently by dynamic code, but the table is not that case. Also you must take in account what I wrote elsewhere, that the registred function (glued to element by events onSomething) are not cloned if the registration is not made by HTML. There is some hack how to do that in FireFox but in MSIE I did not find a cheat.

I am not able to solve your task, because nobody pay me for the analyse, design, coding, debugging and user training. It is your deal. But I try to show some trick rather than guidelines how to do it efficiently :-)

If you allow me an advice: Do not let manipulate yoursef by the user in choosing the resources, algorithm, computational procedures, data structure, and other parts of the process insides. Do your own analyses and never argue if it is good or not to accept the financial model which can count only the positive numbers but differs between credit and debet. It is partially the Roman counting relict, because the Roman numbers were positive only, no zero, and addition and subtraction was not commutative operation! Remember: mathematic and computational science had made great progress from that time :-)
Reply With Quote Quick reply to this message  
Join Date: Apr 2009
Posts: 83
Reputation: nish123 is an unknown quantity at this point 
Solved Threads: 0
nish123's Avatar
nish123 nish123 is offline Offline
Junior Poster in Training

Re: Add/Remove rows from Table

 
0
  #12
Jul 1st, 2009
Sir.. u r real Champ..!!
i dnt knw why u think tht i want to argue...?? i nvr thnk of it.. :O

thanx for the advice... i will surely work on it...!!!
kindly help me in ur code..
When i add a row for the frst time..and then delete it.. this disable the second row...!!!!
i m unable to enter float value in it...!!! and decimal must be enter once...!!!!!!

jst need little help... thnx..!!
Last edited by nish123; Jul 1st, 2009 at 1:48 pm.
Reply With Quote Quick reply to this message  
Join Date: Jun 2009
Posts: 49
Reputation: sysel is an unknown quantity at this point 
Solved Threads: 3
sysel sysel is offline Offline
Light Poster

Re: Add/Remove rows from Table

 
0
  #13
Jul 1st, 2009
Shortly: [code]<input type="button" value="del" onClick="ed(this.parentNode.previousSibling.firstChild); this.parentNode.parentNode.parentNode.deleteRow( this.parentNode.parentNode.rowIndex ); sumus();" disabled="true">[code]need to be replaced so:[code]<input type="button" value="del" onClick="ed(this); this.parentNode.parentNode.parentNode.deleteRow( this.parentNode.parentNode.rowIndex ); sumus();" disabled="true">[code]
Such mistakes are product of adding features after the finish :-)
The programmer's rules says:
- by adding a piece of code, the mistake is always added, too
- by repairing the code, the mistake is added, too
- every code contents at least one mistake
- every code contents at least one useless instruction

-> every code could be reduced to one instruction useless mistake

Are you using decimal comma (',') or point ('.')? Correct the RegExp in the condition (e.g.: /[^\d\.]/) in the check() function, but after that the test will be much more week, because it allows type in the decimal point more time. But I hope it is possible to write the RegExp so clearly to fulfill the goal.
Reply With Quote Quick reply to this message  
Join Date: Jun 2009
Posts: 49
Reputation: sysel is an unknown quantity at this point 
Solved Threads: 3
sysel sysel is offline Offline
Light Poster

Re: Add/Remove rows from Table

 
0
  #14
Jul 1st, 2009
Oh sorry, I used the wrong form and the code was not formated. Hence once again:
JavaScript / DHTML / AJAX Syntax (Toggle Plain Text)
  1. <input type="button" value="del" onClick="ed(this.parentNode.previousSibling.firstChild); this.parentNode.parentNode.parentNode.deleteRow( this.parentNode.parentNode.rowIndex ); sumus();" disabled="true">
reaplace by this:
JavaScript / DHTML / AJAX Syntax (Toggle Plain Text)
  1. <input type="button" value="del" onClick="ed(this); this.parentNode.parentNode.parentNode.deleteRow( this.parentNode.parentNode.rowIndex ); sumus();" disabled="true">

A note: if submitting the form, all disabled items will not be send, hence a short function is written to enable all <INPUT>s before submit().
Reply With Quote Quick reply to this message  
Join Date: Jun 2009
Posts: 49
Reputation: sysel is an unknown quantity at this point 
Solved Threads: 3
sysel sysel is offline Offline
Light Poster

Re: Add/Remove rows from Table

 
0
  #15
Jul 1st, 2009
I think over the float input and found you can rewrite the check() function so:
  1. function check(strt)
  2. { return (parseFloat(strt)!=1*strt && strt!='')?check(strt.slice(0,(strt.length-1))):strt }
Hm, here you can see the difference between the parseFloat conversion and automatic one :-)
Reply With Quote Quick reply to this message  
Join Date: Apr 2009
Posts: 83
Reputation: nish123 is an unknown quantity at this point 
Solved Threads: 0
nish123's Avatar
nish123 nish123 is offline Offline
Junior Poster in Training

Re: Add/Remove rows from Table

 
0
  #16
Jul 2nd, 2009
Originally Posted by sysel View Post
I think over the float input and found you can rewrite the check() function so:
  1. function check(strt)
  2. { return (parseFloat(strt)!=1*strt && strt!='')?check(strt.slice(0,(strt.length-1))):strt }
Hm, here you can see the difference between the parseFloat conversion and automatic one :-)
Thank you Sir, thanks a lot..!!!
yes u r right sir... we cant send values of textbox on submit..until it is Disabled.. So instead of disabled.. can i use ReadOnly attribute.. that will decrease your coding to some extent..!!

your Delete as well as check function is working fine...!!!!
Now i m able to enter float value and decimal once at a time..!!but still i m not able to enter value which starts with decimal.. like(.11)

another thing i m going to use select tag.. does getELementByTagName('input') will accept 'select tag' as input tag..!!
i think no..!! m i right..??
As data of select box comes from database..!! where should i change to make it disable..!!!After Add..!!!

Values of textbox will pass only when when bothside total are same....!!!
So instead of OnKeyUp.. i want to to use Onclick...!!!
Value will add-up on clicking of Add button... because.. i case if you want to edit a field.. then by just writing the value you can make the total same...but i want tht every value should be locked..!! and update the total only when it got locked...!!

I m attaching of small view of my page.. i hope this will give you an Idea what i m want to make..!!

Thanks sir.. for such a great help..!!
Attached Thumbnails
view.JPG  
Reply With Quote Quick reply to this message  
Join Date: Jun 2009
Posts: 49
Reputation: sysel is an unknown quantity at this point 
Solved Threads: 3
sysel sysel is offline Offline
Light Poster

Re: Add/Remove rows from Table

 
0
  #17
Jul 2nd, 2009
There are some methodes I use frequently:
oElColl=  object.getElementsByTagName('tagName');
oElColl=document.getElementsByName(elementName);
oneElmt=document.getElementById(elementId);
Be careful to distinguish between them
- first two give you collection of element even if only one or none was choosen,
- the third gives one only,
-- hence to work with one of a chooesen element can be done as
JavaScript / DHTML / AJAX Syntax (Toggle Plain Text)
  1. oneElmt.value .. .. oneElmt.appendChild(...)
but
oElColl[index].value .. .. oElColl[index].appendChild(...)
- the first can be aplied to any (sub)element
- the two others choose the element(s) from the whole document only
-- it must be taken in account at the beggining of the design: Id must be unique in the document, names (and tags, ofcourse) may repeat, if you make a good distribution into various forms or tables (rows).

Of course,
JavaScript / DHTML / AJAX Syntax (Toggle Plain Text)
  1. oElColl = oForm.getElementsByTagName('select');
gives collection of all <SELECT> elements in specified form.

The check() function may be thinked once over, but not sure when I reach the computer today again :-)
Reply With Quote Quick reply to this message  
Join Date: Jun 2009
Posts: 49
Reputation: sysel is an unknown quantity at this point 
Solved Threads: 3
sysel sysel is offline Offline
Light Poster

Re: Add/Remove rows from Table

 
0
  #18
Jul 2nd, 2009
Yes yes, very nice graphic layout. I always concentrate to the functionality, may be I got less graphic talent :-) But I can recognize the art. (I know about the CSS only that it exists, may be you can give me some lesson :-) )

1) I rewrote the check() function so:
JavaScript / DHTML / AJAX Syntax (Toggle Plain Text)
  1. function check(strt){ return (/^\d*\.?\d*/.exec(strt)==strt)?strt:check(strt.slice(0,(strt.length-1))) }
finally, it gives what you expectted

2) <SELECT> has somewhat other behavior of the <INPUT>. With the oElm.cloneNode(true) where <SELECT> is a subElement of oElm the <INPUT> preserve its value but <SELECT> get its default selected value. In your case it does not matter, but one have to know what to do.

3) I try to prepare to you an example code with a nice trick how to fill the <SELECT> element with <OPTION>s, But sorry, I must find it on my disk :-).
Reply With Quote Quick reply to this message  
Join Date: Apr 2009
Posts: 83
Reputation: nish123 is an unknown quantity at this point 
Solved Threads: 0
nish123's Avatar
nish123 nish123 is offline Offline
Junior Poster in Training

Re: Add/Remove rows from Table

 
0
  #19
Jul 2nd, 2009
Originally Posted by sysel View Post
Yes yes, very nice graphic layout. I always concentrate to the functionality, may be I got less graphic talent :-) But I can recognize the art. (I know about the CSS only that it exists, may be you can give me some lesson :-) )

1) I rewrote the check() function so:
JavaScript / DHTML / AJAX Syntax (Toggle Plain Text)
  1. function check(strt){ return (/^\d*\.?\d*/.exec(strt)==strt)?strt:check(strt.slice(0,(strt.length-1))) }
finally, it gives what you expectted

2) <SELECT> has somewhat other behavior of the <INPUT>. With the oElm.cloneNode(true) where <SELECT> is a subElement of oElm the <INPUT> preserve its value but <SELECT> get its default selected value. In your case it does not matter, but one have to know what to do.

3) I try to prepare to you an example code with a nice trick how to fill the <SELECT> element with <OPTION>s, But sorry, I must find it on my disk :-).
  1. <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
  2. <html dir="ltr"><head>
  3. <title>Journal Entry</title><meta http-equiv="Content-type" content="text/html; charset=ISO-8859-1">
  4. <link href="default.css" rel="stylesheet" type="text/css">
  5. <script type="text/javascript" src="time.js"></script>
  6. <script type="text/javascript" src="currentdate.js"></script>
  7. <script language="JavaScript" src="calendar_us.js"></script>
  8. <link rel="stylesheet" href="calendar.css">
  9. <script type="text/javascript">
  10. var i,d=document;
  11. function add(oRow)
  12. { oRow.parentNode.replaceChild(oRow.cloneNode(true ),oRow.parentNode.insertRow(oRow.rowIndex+1));
  13. var inpS = oRow.getElementsByTagName('select');
  14. var inpR = oRow.getElementsByTagName('input');
  15. var inpN = oRow.nextSibling.getElementsByTagName('input');
  16. for(i=0;i<inpR.length;i++)
  17. {
  18. if(typeof(inpS[i]) != 'undefined') inpS[i].disabled = true;
  19. if(inpR[i].disabled)inpR[i].disabled=false;
  20. if(inpR[i].type=='text'){inpR[i].disabled=true;inpN[i].value=''};
  21. if(inpR[i].value=='add'){inpR[i].value='ed';inpN[i].disabled=true};
  22. }
  23. }
  24. function ed(oBut)
  25. { var trow = oBut.parentNode.parentNode
  26. var inpR = trow.getElementsByTagName('input');
  27. var addrow = trow.parentNode.childNodes[trow.parentNode.lastChild.rowIndex-1]
  28. var addeds = d.getElementsByName('added');
  29. for(i=0;i<inpR.length;i++)
  30. { if(oBut.value=='ed' && inpR[i].type=='text')inpR[i].disabled=false;
  31. if(oBut.value=='lock' && inpR[i].type=='text')inpR[i].disabled=true;
  32. }
  33. if(oBut.value=='ed')
  34. { oBut.value='lock'
  35. for(i=0;i<addeds.length;i++)
  36. { addeds[i].disabled=true;
  37. } oBut.disabled=false;
  38. addrow.childNodes[0].firstChild.disabled=true;
  39. addrow.childNodes[1].firstChild.disabled=true;
  40. } else // oBut.value is not 'lock'
  41. { oBut.value='ed'
  42. for(i=0;i<addeds.length;i++)
  43. { addeds[i].disabled=false;
  44. } emptyStr(addeds[i-1].parentNode.parentNode)
  45. addrow.childNodes[0].firstChild.disabled=false;
  46. addrow.childNodes[1].firstChild.disabled=false;
  47. }
  48. }
  49. function send(oForm)
  50. { var inpF = oForm.getElementsByTagName('input');
  51. for(i=0;i<inpF.length;i++)
  52. { inpF[i].disabled=false;
  53. } //oForm.submit();
  54. }
  55. function check(strt){ return (/^\d*\.?\d*/.exec(strt)==strt)?strt:check(strt.slice(0,(strt.length-1))) }
  56. function emptyStr(oRow)
  57. { var oInpS=oRow.getElementsByTagName('input');var sum1=0,sum2=0;
  58. oInpS[0].value=check(oInpS[0].value);oInpS[1].value=check(oInpS[1].value);
  59. if( oInpS[0].value && !(oInpS[1].value) || oInpS[1].value && !(oInpS[0].value)) oInpS[2].disabled=false;
  60. else oInpS[2].disabled=true;
  61. //sumus();
  62. }
  63. function sumus()
  64. { var sum1=0,sum2=0;
  65. var Col1InpS = d.getElementsByName('row[txt1][]');
  66. var Col2InpS = d.getElementsByName('row[txt2][]');
  67. for(i=0;i<Col1InpS.length;i++)
  68. { sum1+=1*Col1InpS[i].value;sum2+=1*Col2InpS[i].value;
  69. } d.getElementById('s1').innerHTML=sum1;d.getElementById('s2').innerHTML=sum2;
  70. }
  71. function check1()
  72. {
  73.  
  74. if(getElementById('s1').innerHTML != getElementById('s2').innerHTML)
  75. {
  76. alert(getElementById('s1').innerHTML);
  77. alert('total should be matched before proceed');
  78. return false();
  79. }
  80. }
  81. </script>
  82. </HEAD>
  83. <script type="text/javascript" src="tigra_hints.js"></script>
  84. <style>
  85. .hintsClass {
  86. font-family: tahoma, verdana, arial;
  87. font-size: 12px;
  88. background-color: #f3ffff;
  89. color: #000000;
  90. border: 1px solid #808080;
  91. padding: 5px;
  92. }
  93. .hintSource {
  94. color: green;
  95. text-decoration: underline;
  96. cursor: pointer;
  97. }
  98. </style>
  99. <?
  100. $userid = $_SESSION['userid'];
  101. $sql="SELECT * from 0_ledger where group_id not in(1,7) and user_id = $userid";
  102. $result=mysql_query($sql)or die('Query error:'.''.mysql_errno());
  103. ?>
  104. </head>
  105. <body onload="startTime(); currentdate();">
  106. <?php include_once('header.php');
  107. include_once('menu3.php');?>
  108. <script language="JavaScript">
  109.  
  110. // configuration variable for the hint object, these setting will be shared among all hints created by this object
  111. var HINTS_CFG = {
  112. 'wise' : true, // don't go off screen, don't overlap the object in the document
  113. 'margin' : 10, // minimum allowed distance between the hint and the window edge (negative values accepted)
  114. 'gap' : 0, // minimum allowed distance between the hint and the origin (negative values accepted)
  115. 'align' : 'tcbc', // align of the hint and the origin (by first letters origin's top|middle|bottom left|center|right to hint's top|middle|bottom left|center|right)
  116. 'css' : 'hintsClass', // a style class name for all hints, applied to DIV element (see style section in the header of the document)
  117. 'show_delay' : 50, // a delay between initiating event (mouseover for example) and hint appearing
  118. 'hide_delay' : 50, // a delay between closing event (mouseout for example) and hint disappearing
  119. 'follow' : false, // hint follows the mouse as it moves
  120. 'z-index' : 100, // a z-index for all hint layers
  121. 'IEfix' : false, // fix IE problem with windowed controls visible through hints (activate if select boxes are visible through the hints)
  122. 'IEtrans' : ['blendTrans(DURATION=.3)', 'blendTrans(DURATION=.3)'], // [show transition, hide transition] - nice transition effects, only work in IE5+
  123. 'opacity' : 100 // opacity of the hint in %%
  124. };
  125. // text/HTML of the hints
  126. var HINTS_ITEMS = [
  127. 'Date Should not be of Future',
  128. 'If Last Actual Budget is Null then <br> it means no entry is passed in last month',
  129. 'tooltip for item3<br>This one is multi line',
  130. 'tooltip for item4',
  131. 'another sample tooltip with the <a href="http://www.softcomplex.com">link</a>'
  132. ];
  133.  
  134. var myHint = new THints(HINTS_ITEMS, HINTS_CFG);
  135. </script>
  136. <div class="clear">
  137. </div>
  138. <div id="menu2">
  139. <ul>
  140. <li><a href="entry.php" style="font-family:Verdana, Arial, Helvetica, sans-serif; font-size:14px">Journal Entry</a></li>
  141. <li><a href="payment.php" style="font-family:Verdana, Arial, Helvetica, sans-serif; font-size:14px">Payments</a></li>
  142. <li><a href="deposit.php" style="font-family:Verdana, Arial, Helvetica, sans-serif; font-size:14px">Receipts</a></li>
  143. <li><a href="showgl.php" style="font-family:Verdana, Arial, Helvetica, sans-serif; font-size:14px">View Journal Entries </a></li>
  144. <li><a href="contra.php" style="font-family:Verdana, Arial, Helvetica, sans-serif; font-size:14px">Contra Entry</a></li>
  145. </ul>
  146. </div>
  147. <div class="clear"></div>
  148. <center>
  149. <table border="0" width="100%">
  150. <tr>
  151. <td width="20%"><font face="Courier New, Courier, mono" size="+1"><b>Journal Entry</b></font></td>
  152. <td align="center" width="50%"><b> Welcome&nbsp;&nbsp;<?= $_SESSION['username'];?></b></td>
  153. <td align="right"><div id="txt1"></div></td>
  154. </tr>
  155. <tr>
  156. <td class="titletext" style="">&nbsp;</td>
  157. <td align="right" class="titletext" colspan="2">Time:<span id="txt"></span></td>
  158. </tr>
  159. </table>
  160. </center>
  161. </center>
  162. <div class="clear"></div>
  163. <br><?include_once('msgbox.php'); ?>
  164.  
  165.  
  166. <form method="post" name='testform' action="" onsubmit="return validate();">
  167. <center>
  168. <table style="border-collapse: collapse;" width="50%" bgcolor="#f9f9f9" border="0" bordercolor="#cccccc" cellpadding="3" cellspacing="0">
  169. <input type="hidden" name='type' id='type' value="Journal">
  170. <tr>
  171. <td width="50%" align="right"><b>Date:</b></td>
  172. <td><input type="text" value="<?=$_POST['testinput']; ?>" name="testinput" readonly="readonly" onmouseover="myHint.show(0, this)" onmouseout="myHint.hide()" />
  173. <script language="JavaScript">
  174. new tcal ({
  175. // form name
  176. 'formname': 'testform',
  177. // input name
  178. 'controlname': 'testinput'
  179. });
  180.  
  181. </script>
  182. </a>
  183. </td>
  184. </tr>
  185. </table></center>
  186. <br><center>
  187. <table style="border-collapse: collapse;" id="tblSample" width="95%" bgcolor="#f9f9f9" border="1" bordercolor="#cccccc" cellpadding="3" cellspacing="0" id="testtable">
  188. <tr>
  189. <td colspan="4"><center><span class="headingtext">Transactions</span></center></td>
  190. </tr>
  191. <tr>
  192. <td class="tableheader">Account Description</td>
  193. <td class="tableheader">Debit</td>
  194. <td class="tableheader">Credit</td>
  195. <td class="tableheader">&nbsp;</td>
  196. </tr>
  197. <tr class="evenrow" id='tr3'>
  198. <td align="center">
  199. <select id="row[txt0][]" name="row[txt0][]" style="width:130px" onchange="return myPopup2();">
  200. <? while($row=mysql_fetch_array($result)) { ?>
  201. <option value="<?=$row['ledger_id']?>"><?=$row['ledgerName'];?></option>
  202. <?}?>
  203. <option value="2">Add New Ledger</option>
  204. </select>
  205. </td>
  206. <td><input type="text" name="row[txt1][]" onKeyUp="this.value=check(this.value); emptyStr(this.parentNode.parentNode)" onBlur="emptyStr(this.parentNode.parentNode)" ></td>
  207. <td><input type="text" name="row[txt2][]" onKeyUp="this.value=check(this.value); emptyStr(this.parentNode.parentNode)" onBlur="emptyStr(this.parentNode.parentNode)"></td>
  208. <td><input type="button" name="added" value="add" onClick="(this.value=='add')?add( this.parentNode.parentNode ):ed(this);sumus(); " disabled="true">
  209. <input type="button" value="del" onClick="ed(this); this.parentNode.parentNode.parentNode.deleteRow( this.parentNode.parentNode.rowIndex ); sumus();" disabled="true"></td>
  210. </tr>
  211. <tr>
  212. <th>Total</th>
  213. <td id="s1"></td>
  214. <td id="s2"></td>
  215. <td></td></tr></tbody></table>
  216. </center>
  217. </div><br><table align="center"><tbody><tr><td><b>Narration:</b></td>
  218. <td>
  219. <textarea cols="40" rows="3" name="narration" id='narration'><?=$_POST['narration']?></textarea></td>
  220. </tr> <input type="hidden" name="counter" id="counter">
  221. </tbody>
  222. </table>
  223. </td>
  224. </tr>
  225. </tbody>
  226. </table>
  227. </center>
  228. <br><center><input onclick='return check1();' class="ajaxsubmit" name="Process" id="Process" value="Process Journal Entry" title="Process journal entry only if debits equal to credits" type="submit">
  229. </center>
  230. </form>
  231. </div><br><div id="footer">
  232. <? include_once('footer.html'); ?>
  233. </body>
  234. </html>

This is my almost done code... i made few changes in it...but what problem i m facing now that it does not work on Firefox..!! my bad luck..!! its showing weird behavior in firefox... like add button does nt disable for first time... when i click on it changes to edit button..!!



i m attaching a screenshot of firefox view...!!!

Thanks Sir for your Support
Last edited by nish123; Jul 2nd, 2009 at 3:37 pm.
Reply With Quote Quick reply to this message  
Join Date: Jun 2009
Posts: 49
Reputation: sysel is an unknown quantity at this point 
Solved Threads: 3
sysel sysel is offline Offline
Light Poster

Re: Add/Remove rows from Table

 
0
  #20
Jul 2nd, 2009
As I promised, I pulled out a piece of code and added it into the exaple, to show you a nice trick, how to create an option list very easy and clearly. As I added the <SELECT> column, it cause me to change somewhat the other routine, but I hope you can find and understand.

To show the powerful dynamic <OPTION> fill I adopted the function knockOut() for to trim the option list at each <SELECT> cleared of the used items. May be it is coded in 'lama' style, because in hurry :-) But for the understanding the javascript 1.2 it is sufficient. I hope.

I put here my version of code with a short PHP 'loader'. Your coding is very clear, good formated and commented. It gives you good chances to return back to your code and easy to repair it if necessary. Points for you! I see, I can easy introduce myself into the CSS from your code, too. Thanks.

JavaScript / DHTML / AJAX Syntax (Toggle Plain Text)
  1. <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
  2. <HTML><HEAD>
  3. <META http-equiv="content-type" content="text/html; charset=UTF-8">
  4. <meta http-equiv="Content-Script-Type" content="text/javascript">
  5. <TITLE>add/ed/del row</TITLE><?php ?> <?php /*comments*/?>
  6. <?php
  7. if($row=$_POST['row'])
  8. { foreach($row as $k => $v)
  9. { foreach($v as $kk => $vv)
  10. { $wor[$kk][$k]=$vv;
  11. };
  12. };
  13. } else $wor="";
  14.  
  15. $arrBrand=array(1=>"Electricity"
  16. ,2=>"Water"
  17. ,3=>"Gas"
  18. ,4=>"Appartement Rent"
  19. ,5=>"School Fee");
  20. /** $arrayBrand can be get from a database
  21. $res=mysql_query("SELECT distinct brand FROM table");
  22. $i=0;while($cols = mysql_fetch_row($dbResult))
  23. {$line[$i]="'$i':['$i++','".$cols[0]."']";
  24. }
  25. //*/
  26. foreach($arrBrand as $kk => $vv){ $line[]="'$kk':['$kk','$vv']";}
  27. $optOut="\n{".implode("\n,",$line)."}";
  28. ////oSel.length = 0;
  29. ?>
  30. <script>
  31. var i,d=document;
  32. /*********************************************************************/
  33. var oOpts = <?php print $optOut ?>; // move the set of Options into a JS object!
  34.  
  35. function add_option(what,where) // to define and add one Option
  36. { var nop = d.createElement('option');
  37. nop.innerHTML = what[1]; // nop.text does not accept MSIE
  38. nop.value = what[0];
  39. nop.title = nop.alt = what[0]; // showes the option value as 'bubble'
  40. where.appendChild(nop);
  41. }
  42. function fill_sell(oSel,oSet,oExept) // to clear and fill back the Option set
  43. { if(oExept==undefined)oExept={}; // except used ones
  44. var myVal='';if(oSel.length>1){ myVal=oSel.value; oSel.length = 1; }
  45. for(var l in oSet)
  46. { if( (l==myVal) || !(l in oExept) ) add_option(oSet[l],oSel);
  47. } oSel.value=myVal;
  48. }
  49. function knockOut(formChild) // to trim the each <select> option list
  50. { var selOpt=collect(formChild.form);
  51. var selAll = formChild.form.getElementsByTagName('select');
  52. var selNew = selAll[selAll.length-1];
  53. if(formChild.nodeName=='SELECT') selNew = formChild;
  54. for(i=0;i<selAll.length;i++) fill_sell(selAll[i], oOpts, collect(selAll[i].form));
  55. }
  56. function collect(frm) // to create an object from all used values
  57. { var selVar = {};
  58. var selAll = frm.getElementsByTagName('select');
  59. for(var k=0;k < selAll.length ;k++)
  60. { if(selAll[k].length>1 && (selAll[k].value in oOpts)) selVar[selAll[k].value]=selAll[k].selectedIndex;
  61. } return selVar;
  62. }
  63. /**********************************************************************/
  64.  
  65. function add(oRow)
  66. { oRow.parentNode.replaceChild(oRow.cloneNode(true ),oRow.parentNode.insertRow(oRow.rowIndex+1));
  67. var inpR = oRow.getElementsByTagName('input');
  68. var inpN = oRow.nextSibling.getElementsByTagName('input');
  69. var selR = oRow.getElementsByTagName('select')[0];
  70. selR.disabled=true;
  71. var selN = oRow.nextSibling.getElementsByTagName('select')[0];
  72. selN.length = 1;
  73. for(i=0;i<inpR.length;i++)
  74. { if(inpR[i].disabled)inpR[i].disabled=false;
  75. if(inpR[i].type=='text'){inpR[i].disabled=true;inpN[i].value=''};
  76. if(inpR[i].value=='add'){inpR[i].value='ed';inpN[i].disabled=true};
  77. } sumus();knockOut(selN);
  78. }
  79.  
  80. function ed(oBut)
  81. { var nextSel = oBut.parentNode.parentNode.nextSibling.firstChild.firstChild;
  82. var trow = oBut.parentNode.parentNode;
  83. var inpR = trow.getElementsByTagName('input');
  84. var selR = trow.getElementsByTagName('select')[0];
  85. var addrow = trow.parentNode.childNodes[trow.parentNode.lastChild.rowIndex-1]
  86. var addeds = d.getElementsByName('added');
  87. for(i=0;i<inpR.length;i++)
  88. { if(oBut.value=='ed' && inpR[i].type=='text'){inpR[i].disabled=false;selR.disabled=false;}
  89. if(oBut.value=='lock' && inpR[i].type=='text'){inpR[i].disabled=true; selR.disabled=true;}
  90. }
  91. if(oBut.value=='ed')
  92. { oBut.value='lock'
  93. for(i=0;i<addeds.length;i++)
  94. { addeds[i].disabled=true;
  95. } oBut.disabled=false;
  96. addrow.childNodes[0].firstChild.disabled=true;
  97. addrow.childNodes[1].firstChild.disabled=true;
  98. addrow.childNodes[2].firstChild.disabled=true;
  99. } else // oBut.value is not 'lock'
  100. { oBut.value='ed'
  101. for(i=0;i<addeds.length;i++)
  102. { addeds[i].disabled=false;
  103. } emptyStr(addeds[i-1].parentNode.parentNode)
  104. addrow.childNodes[0].firstChild.disabled=false;
  105. addrow.childNodes[1].firstChild.disabled=false;
  106. addrow.childNodes[2].firstChild.disabled=false;
  107. } knockOut(nextSel);
  108. //alert(nextSel);
  109. }
  110. function send(oForm)
  111. { var inpF = oForm.getElementsByTagName('input');
  112. for(i=0;i<inpF.length;i++)
  113. { inpF[i].disabled=false;
  114. } oForm.submit();
  115. } function check(strt){ return (/^\d*\.?\d*/.exec(strt)==strt)?strt:check(strt.slice(0,(strt.length-1))) }
  116. function emptyStr(oRow)
  117. { var oInpS =oRow.getElementsByTagName('input');var sum1=0,sum2=0;
  118. oInpS[0].value=check(oInpS[0].value); oInpS[1].value=check(oInpS[1].value);
  119. if( oInpS[0].value && !(oInpS[1].value) || oInpS[1].value && !(oInpS[0].value))
  120. oInpS[2].disabled=false;
  121. else oInpS[2].disabled=true;
  122. sumus();
  123. }
  124. function sumus()
  125. { var sum1=0,sum2=0;
  126. var Col1InpS = d.getElementsByName('row[credit][]');
  127. var Col2InpS = d.getElementsByName('row[debet][]');
  128. for(i=0;i<Col1InpS.length;i++)
  129. { sum1+=1*Col1InpS[i].value;sum2+=1*Col2InpS[i].value;
  130. } d.getElementById('s1').innerHTML=sum1;d.getElementById('s2').innerHTML=sum2;
  131. }
  132. </script>
  133. </HEAD>
  134. <BODY><form method="post" action="./fuj.php">
  135. <table><tbody><tr><td><select name="row[brand][]" onChange="knockOut(this)"><option value="" disabled="true">Choose one</option></td><td><input type="text" name="row[credit][]" onKeyUp=" emptyStr(this.parentNode.parentNode)" onBlur="emptyStr(this.parentNode.parentNode)" ></td><td><input type="text" name="row[debet][]" onKeyUp="this.value=check(this.value); emptyStr(this.parentNode.parentNode)" onBlur="emptyStr(this.parentNode.parentNode)"></td><td><input type="button" name="added" value="add" onClick="(this.value=='add')?add( this.parentNode.parentNode ):ed(this) " disabled="true"></td><td><input type="button" value="del" onClick="var nextSel = this.parentNode.parentNode.nextSibling.firstChild.firstChild; ed(this); this.parentNode.parentNode.parentNode.deleteRow( this.parentNode.parentNode.rowIndex ); sumus(); knockOut(nextSel);" disabled="true"></td></tr><tr><td></td><td id="s1"></td><td id="s2"></td><td></td><td></td></tr></tbody></table>
  136. <br><input type="button" value="send" onClick="send(this.form)">
  137. <script>fill_sell(d.getElementsByTagName('select')[0],oOpts)</script>
  138. </form><br>
  139. <?php print_r($_POST["row"]);print_r($wor);?>
  140. </BODY>
  141. </HTML>
Reply With Quote Quick reply to this message  
Reply

This thread is more than three months old.
Perhaps start a new thread instead?
Message:


Thread Tools Search this Thread



About Us | Contact Us | Advertise | DaniWeb | Acceptable Use Policy | RSS Feed

©2003 - 2009 DaniWeb® LLC