954,597 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?
Have something to say? Contribute New Article Reply to this Article

Add/Remove rows from Table

Hello Frndz i m in complete mess...

i have to a table with Add/Remove rows features...
it should look like this -

textbox1 | textbox2 | Add Button


after clicking the add button Row will append and Disable the textbox with values...!!!

It looks like this after clickin Add Button..

textbox1 disabled | textbox1 disabled | Edit/Delete button
textbox2 | textbox2 | Add Button


Any Help will be appriciated..!!

nish123
Junior Poster in Training
83 posts since Apr 2009
Reputation Points: 10
Solved Threads: 0
 

cool, so where is the code?

sillyboy
Practically a Master Poster
686 posts since Mar 2007
Reputation Points: 85
Solved Threads: 64
 

yeah i m also asking for the code only..!! :D

nish123
Junior Poster in Training
83 posts since Apr 2009
Reputation Points: 10
Solved Threads: 0
 

please Check my thread which will give you idea that how to show edit and delete Button for all records. and Last code of the thread show the dtat in textfields and u can update each recodrd,
if helpful then mark thread as Solved.
Here is a link
http://www.daniweb.com/forums/thread199644.html

ayesha789
Posting Pro in Training
496 posts since Jun 2009
Reputation Points: 17
Solved Threads: 7
 

Ayesha..
It is useful thread...but i want it in javascript....!!! i m making a small accounting web application.. i want it to enter multiple transactions...!!!

nish123
Junior Poster in Training
83 posts since Apr 2009
Reputation Points: 10
Solved Threads: 0
 

Here you are the code:

<HTML><HEAD>
<META http-equiv="content-type" content="text/html; charset=UTF-8">
<TITLE>add/ed/del row</TITLE>
<script>

function add(oRow) 
{ oRow.parentNode.replaceChild(oRow.cloneNode(true ),oRow.parentNode.insertRow(oRow.rowIndex+1));
  var inpN = oRow.nextSibling.getElementsByTagName('input');
  var inpR = oRow.getElementsByTagName('input');
  for(var i=0;i<inpR.length;i++)
  { if(inpN[i].disabled)inpN[i].disabled=false;
    if(inpR[i].type=='text')inpR[i].disabled=true;
    if(inpR[i].value=='add')inpR[i].value='ed';
  };
}
function ed(oRow)
{ var inpR = oRow.getElementsByTagName('input');
    for(var i=0;i<inpR.length;i++)
  { inpR[i].disabled=false;
  }
}
</script>
</HEAD>
<BODY><form method="post" action="./finalPage.php">
<table><tbody><tr><td><input type="text" name="row[txt1][]"></td><td><input type="text" name="row[txt2][]"></td><td><input type="button" value="add" onClick="(this.value=='add')?add(this.parentNode.parentNode):ed(this.parentNode.parentNode)"></td><td><input type="button" value="del" onClick="this.parentNode.parentNode.parentNode.deleteRow(this.parentNode.parentNode.rowIndex)" disabled="true"></td></tr></tbody></table>
</form>

</BODY>
</HTML>

But! What will you do with the data after the formula is fulfilled? Is the data to be processed at the same page using another JavaScript? or there have to be a button for sending the data to a process page?
You asked for the change the button "add" into the "edit". What will you do after you'll be finished with the row editing? Could not be the "ed" button change into the "lock" button while editing the row?

Think it over, before you start to code and asking the help!

sysel
Light Poster
49 posts since Jun 2009
Reputation Points: 11
Solved Threads: 3
 

As I am takinkg off the Internet, I drop down here the revised code:

<HTML><HEAD>
<META http-equiv="content-type" content="text/html; charset=UTF-8">
<TITLE>add/ed/del row</TITLE>
<script>

function add(oRow) 
{ oRow.parentNode.replaceChild(oRow.cloneNode(true ),oRow.parentNode.insertRow(oRow.rowIndex+1));
//  var inpN = oRow.nextSibling.getElementsByTagName('input');
  var inpR = oRow.getElementsByTagName('input');
  for(var i=0;i<inpR.length;i++)
  { if(inpR[i].disabled)inpR[i].disabled=false;
    if(inpR[i].type=='text')inpR[i].disabled=true;
    if(inpR[i].value=='add')inpR[i].value='ed';
  };
}
function ed(oBut)
{ var inpR = oBut.parentNode.parentNode.getElementsByTagName('input');
  for(var i=0;i<inpR.length;i++)
  { if(oBut.value=='ed' && inpR[i].type=='text')inpR[i].disabled=false;
    if(oBut.value=='lock' && inpR[i].type=='text')inpR[i].disabled=true;
  } if(oBut.value=='ed'){oBut.value='lock'}else{oBut.value='ed'}
}
function send(oForm)
{ var inpF = oForm.getElementsByTagName('input');
  for(var i=0;i<inpF.length;i++)
  { inpF[i].disabled=false;
  } oForm.submit();
}
</script>
</HEAD>
<BODY><form method="post" action="./fuj.php">
<table><tbody><tr><td><input type="text" name="row[txt1][]"></td><td><input type="text" name="row[txt2][]"></td><td><input type="button" value="add" onClick="(this.value=='add')?add( this.parentNode.parentNode ):ed(this) "></td><td><input type="button" value="del" onClick="this.parentNode.parentNode.parentNode.deleteRow( this.parentNode.parentNode.rowIndex )" disabled="true"></td></tr></tbody></table>
<input type="button" value="send" onClick="send(this.form)">
</form>
<?php print_r($_POST["row"])?>
</BODY>
</HTML>


Save the page as thefuj.php and it shows you what you had input before send (if you have PHP module enabled on your server, of course).
See you after some hours :-)

sysel
Light Poster
49 posts since Jun 2009
Reputation Points: 11
Solved Threads: 3
 

As I am takinkg off the Internet, I drop down here the revised code:

<HTML><HEAD>
<META http-equiv="content-type" content="text/html; charset=UTF-8">
<TITLE>add/ed/del row</TITLE>
<script>

function add(oRow) 
{ oRow.parentNode.replaceChild(oRow.cloneNode(true ),oRow.parentNode.insertRow(oRow.rowIndex+1));
//  var inpN = oRow.nextSibling.getElementsByTagName('input');
  var inpR = oRow.getElementsByTagName('input');
  for(var i=0;i<inpR.length;i++)
  { if(inpR[i].disabled)inpR[i].disabled=false;
    if(inpR[i].type=='text')inpR[i].disabled=true;
    if(inpR[i].value=='add')inpR[i].value='ed';
  };
}
function ed(oBut)
{ var inpR = oBut.parentNode.parentNode.getElementsByTagName('input');
  for(var i=0;i<inpR.length;i++)
  { if(oBut.value=='ed' && inpR[i].type=='text')inpR[i].disabled=false;
    if(oBut.value=='lock' && inpR[i].type=='text')inpR[i].disabled=true;
  } if(oBut.value=='ed'){oBut.value='lock'}else{oBut.value='ed'}
}
function send(oForm)
{ var inpF = oForm.getElementsByTagName('input');
  for(var i=0;i<inpF.length;i++)
  { inpF[i].disabled=false;
  } oForm.submit();
}
</script>
</HEAD>
<BODY><form method="post" action="./fuj.php">
<table><tbody><tr><td><input type="text" name="row[txt1][]"></td><td><input type="text" name="row[txt2][]"></td><td><input type="button" value="add" onClick="(this.value=='add')?add( this.parentNode.parentNode ):ed(this) "></td><td><input type="button" value="del" onClick="this.parentNode.parentNode.parentNode.deleteRow( this.parentNode.parentNode.rowIndex )" disabled="true"></td></tr></tbody></table>
<input type="button" value="send" onClick="send(this.form)">
</form>
<?php print_r($_POST["row"])?>
</BODY>
</HTML>
Save the page as thefuj.php and it shows you what you had input before send (if you have PHP module enabled on your server, of course). See you after some hours :-)


Bravo Maan... exactly wht i looking for... but still there are few validation tht i want in it.... Can u guide me little bit...!!!
i will be thankful to u...!!!
Validation are like this-
1) At least one row and only one row should be Fillled before adding a new row..!!!Value must be integers..!!
2)At the bottom of table there are two textboxes which total the amount of textboxes in Table..!!
3)When Edit button is pressed then add button should be hide...until the row is updated...!!!
4) After update and delete total amount should be update..

nish123
Junior Poster in Training
83 posts since Apr 2009
Reputation Points: 10
Solved Threads: 0
 

Hi, it could be very useful, if you first wrote a simple HTML skeleton of the page even free of the scripts and features, but with the fully unique named items and/or with id. Than it could be much more simple to explain, what is the goal of the programming the features.

Here you are the page, and try to use it not for simple copy/pasting but for learning.

As I do not use MSIE I definitely cannot find out why Exploder does not show it.

sysel
Light Poster
49 posts since Jun 2009
Reputation Points: 11
Solved Threads: 3
 

Hi, it could be very useful, if you first wrote a simple HTML skeleton of the page even free of the scripts and features, but with the fully unique named items and/or with id. Than it could be much more simple to explain, what is the goal of the programming the features.

Here you are the page, and try to use it not for simple copy/pasting but for learning.

As I do not use MSIE I definitely cannot find out why Exploder does not show it.

tht was almost the perfect function....!!!! Thank u so much..!!
but sir i said only one text box from a row should be filled not both the fields...!!!
and there is one more field in which i m using dropdown and data coming from database...!!
another flaws i found tht when i edit a row..add button got disable and new lock button came in place of edit....but instead of edit if i delete the row... Add button still remain disable...!!!! i hpoe u got my point
but still its a gr8 function.....!!!!!
This javascript function i used for my work but it has lot of flaws..!!

function addRowToTable() 
{    
   // alert(document.getElementById('tblSample').getElementsByTagName('tr').length);
  var tbl = document.getElementById('tblSample');
  var lastRow = tbl.rows.length;
  // if there's noheader row in the table, then iteration = lastRow + 1
  var iteration = lastRow;     
  var iteration1 = parseInt(lastRow+1);  
  
  alert(iteration1);
  //Validate for empty check 
//  var iteration = parseFloat(iteration-1); 

  for(var i=3;i<=iteration1;i++)  
  { 
    if($('debit'+i)!=null)
    {                  
        if($('debit'+i).value.trim() == '' && $('credit'+i).value.trim() != '')
        {    
            $('debit'+i).readOnly = true;
            $('credit'+i).readOnly = true;
            $('dledger'+i).disabled = true;
        }
        else if($('credit'+i).value.trim() == '' && $('debit'+i).value.trim() != '')
        { 
            $('credit'+i).readOnly = true;     
            $('debit'+i).readOnly = true;     
            $('dledger'+i).disabled = true;
        }
    }
  }   
  var debitTotal = 0;
  var creditTotal = 0;          
                         
   if($('debit'+iteration).value.trim() == '' && $('credit'+iteration).value.trim() == '')
    {
        alert('Please enter debit/credit value');
        return false;
    }
  if($('debit'+iteration).value != '' && $('credit'+iteration).value != '')
  {
    alert('Please enter only debit/credit value');
    return false;
  } 
  for(var i=3;i<=iteration1;i++)
  {  
    if($('debit'+i).value != ''){
        debitTotal = parseFloat(debitTotal) + parseFloat($('debit'+i).value);
    }
    if($('credit'+i).value != ''){
        creditTotal = parseFloat(creditTotal) + parseFloat($('credit'+i).value);
    }
  }        
  $('tdebit').value = debitTotal;
  $('tcredit').value = creditTotal;                    
  document.getElementById('counter').value=iteration-3;
  var row = tbl.insertRow(lastRow);
  row.id = 'tr_'+iteration1;
  // left cell 
// cellRightSel.appendChild(sel); 
  // right cell
  
  
  var cellRightSel = row.insertCell(0); 
  var sel = document.createElement('select');
  sel.id ='dledger' + iteration1;
  sel.name ='dledger' + iteration1;
  cellRightSel.align = 'center';
  sel.style.width = 125; 
  //sel.size = 100;
  <? 
    $userid = $_SESSION['userid'];
    $sql="SELECT * from 0_ledger where group_id not in(1,7) and user_id = $userid";
    $result=mysql_query($sql)or die('Query error:'.''.mysql_errno());   
    $counter=0; 
    while($row=mysql_fetch_array($result))
        {?>
        sel.options[<?= $counter; ?>] = new Option('<?= $row['ledgerName']?>', '<?=$row['ledger_id']?>');
        <? $counter = $counter + 1;  
    }?>  
  cellRightSel.appendChild(sel); 
  
  var cellRight = row.insertCell(1);
  cellRight.align = 'center';
  var el = document.createElement('input');
  el.type = 'text';
  el.name = 'debit' + iteration1;
  el.id = 'debit' + iteration1;
  el.size = 20; 
  el.maxLength = 8;
  cellRight.appendChild(el);
  
 /* var cellRightSel = row.insertCell(2);
  var sel = document.createElement('select');
  sel.name = 'selRow' + iteration;
  sel.options[0] = new Option('text zero', 'value0');
  sel.options[1] = new Option('text one', 'value1');
  cellRightSel.appendChild(sel);  */ 
  
    var cellRight2 = row.insertCell(2);
    cellRight2.align='center';
    var el2 = document.createElement('input');
    el2.type = 'text';
    el2.name = 'credit' + iteration1;
    el2.id = 'credit' + iteration1;
    el2.size = 20;
    el2.maxLength = 8; 
 
    cellRight2.appendChild(el2);  
    
     var cellLeft = row.insertCell(3);
     cellLeft.align = 'center';   
     cellLeft.id  = 'td'+iteration1;
    var chbk1 = document.createElement('span');
     chbk1.id = 'change'+iteration1;
    var chbk = document.createElement('input');
    chbk.type = 'button';
    chbk.name = 'additem'+iteration1;
    
    chbk.id = 'additem'+iteration1;
    chbk.className = 'ajaxsubmit';
    chbk.value = 'Add Item';
    //chbk.disabled = true; 
    //.onClick = function(){addRowToTable();};
    chbk.onclick = function(){addRowToTable1();change();};
    //chbk.setAttribute('onClick','addRowToTable1();change()');
    cellLeft.appendChild(chbk1);   
    cellLeft.appendChild(chbk);  
     
  
}
nish123
Junior Poster in Training
83 posts since Apr 2009
Reputation Points: 10
Solved Threads: 0
 

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 s on a single row, where the user clicked the button, simply collect those inputs:

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 :-)

sysel
Light Poster
49 posts since Jun 2009
Reputation Points: 11
Solved Threads: 3
 

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..!! :)

nish123
Junior Poster in Training
83 posts since Apr 2009
Reputation Points: 10
Solved Threads: 0
 

Shortly: [code][code]need to be replaced so:[code][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.

sysel
Light Poster
49 posts since Jun 2009
Reputation Points: 11
Solved Threads: 3
 

Oh sorry, I used the wrong form and the code was not formated. Hence once again:

<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:

<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 s before submit().

sysel
Light Poster
49 posts since Jun 2009
Reputation Points: 11
Solved Threads: 3
 

I think over the float input and found you can rewrite the check() function so:

function check(strt)
{ 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 :-)

sysel
Light Poster
49 posts since Jun 2009
Reputation Points: 11
Solved Threads: 3
 

I think over the float input and found you can rewrite the check() function so:

function check(strt)
{ 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..!! :)

Attachments view.JPG 24.1KB
nish123
Junior Poster in Training
83 posts since Apr 2009
Reputation Points: 10
Solved Threads: 0
 

There are some methodes I use frequently:

oElColl=  object.getElement<strong>s</strong>ByTagName('<em>tagName</em>');
oElColl=document.getElement<strong>s</strong>ByName(<em>elementName</em>);
oneElmt=document.getElementById(<em>elementId</em>);

Be careful to distinguish between them
- first two give youcollection 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

oneElmt.value  .. .. oneElmt.appendChild(...)

but

oElColl[<em>index</em>].value .. .. oElColl[<em>index</em>].appendChild(...)

- the first can be aplied to any (sub)element
- the two others choose the element(s) from the wholedocument 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,

oElColl = oForm.getElementsByTagName('select');


gives collection of all elements in specified form.

The check() function may be thinked once over, but not sure when I reach the computer today again :-)

sysel
Light Poster
49 posts since Jun 2009
Reputation Points: 11
Solved Threads: 3
 

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:

function check(strt){ return (/^\d*\.?\d*/.exec(strt)==strt)?strt:check(strt.slice(0,(strt.length-1))) }


finally, it gives what you expectted

2) has somewhat other behavior of the . With the oElm.cloneNode(true) where is a subElement of oElm the preserve its value but 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 element with s, But sorry, I must find it on my disk :-).

sysel
Light Poster
49 posts since Jun 2009
Reputation Points: 11
Solved Threads: 3
 

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:

function check(strt){ return (/^\d*\.?\d*/.exec(strt)==strt)?strt:check(strt.slice(0,(strt.length-1))) }

finally, it gives what you expectted

2) has somewhat other behavior of the . With the oElm.cloneNode(true) where is a subElement of oElm the preserve its value but 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 element with s, But sorry, I must find it on my disk :-).

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html dir="ltr"><head>
<title>Journal Entry</title><meta http-equiv="Content-type" content="text/html; charset=ISO-8859-1">
<link href="default.css" rel="stylesheet" type="text/css"> 
<script type="text/javascript" src="time.js"></script>
<script type="text/javascript" src="currentdate.js"></script>
<script language="JavaScript" src="calendar_us.js"></script>
    <link rel="stylesheet" href="calendar.css">
<script type="text/javascript">    
var i,d=document;
function add(oRow) 
{ oRow.parentNode.replaceChild(oRow.cloneNode(true ),oRow.parentNode.insertRow(oRow.rowIndex+1));
  var inpS = oRow.getElementsByTagName('select');
  var inpR = oRow.getElementsByTagName('input');
  var inpN = oRow.nextSibling.getElementsByTagName('input');
  for(i=0;i<inpR.length;i++)
  {     
    if(typeof(inpS[i]) != 'undefined') inpS[i].disabled = true;  
    if(inpR[i].disabled)inpR[i].disabled=false;
    if(inpR[i].type=='text'){inpR[i].disabled=true;inpN[i].value=''};
    if(inpR[i].value=='add'){inpR[i].value='ed';inpN[i].disabled=true};
  } 
}
function ed(oBut)
{ var trow = oBut.parentNode.parentNode
  var inpR = trow.getElementsByTagName('input');
  var addrow = trow.parentNode.childNodes[trow.parentNode.lastChild.rowIndex-1]
  var addeds = d.getElementsByName('added');
  for(i=0;i<inpR.length;i++)
  { if(oBut.value=='ed' && inpR[i].type=='text')inpR[i].disabled=false;
    if(oBut.value=='lock' && inpR[i].type=='text')inpR[i].disabled=true;
  } 
  if(oBut.value=='ed')
  { oBut.value='lock'
    for(i=0;i<addeds.length;i++)
    { addeds[i].disabled=true;
    } oBut.disabled=false;
    addrow.childNodes[0].firstChild.disabled=true;
    addrow.childNodes[1].firstChild.disabled=true;
  } else // oBut.value is not 'lock'
  { oBut.value='ed'
    for(i=0;i<addeds.length;i++)
    { addeds[i].disabled=false;
    } emptyStr(addeds[i-1].parentNode.parentNode)
    addrow.childNodes[0].firstChild.disabled=false;
    addrow.childNodes[1].firstChild.disabled=false;
  } 
}
function send(oForm)
{ var inpF = oForm.getElementsByTagName('input');
  for(i=0;i<inpF.length;i++)
  { inpF[i].disabled=false;
  } //oForm.submit();
}
        function check(strt){ return (/^\d*\.?\d*/.exec(strt)==strt)?strt:check(strt.slice(0,(strt.length-1))) }
function emptyStr(oRow)
{ var oInpS=oRow.getElementsByTagName('input');var sum1=0,sum2=0;
      oInpS[0].value=check(oInpS[0].value);oInpS[1].value=check(oInpS[1].value);
  if( oInpS[0].value && !(oInpS[1].value) || oInpS[1].value && !(oInpS[0].value)) oInpS[2].disabled=false;
  else                                  oInpS[2].disabled=true;
  //sumus();
}
function sumus()
{ var sum1=0,sum2=0;
  var Col1InpS = d.getElementsByName('row[txt1][]');
  var Col2InpS = d.getElementsByName('row[txt2][]');
  for(i=0;i<Col1InpS.length;i++)
  { sum1+=1*Col1InpS[i].value;sum2+=1*Col2InpS[i].value;
  } d.getElementById('s1').innerHTML=sum1;d.getElementById('s2').innerHTML=sum2;
}
function check1()
{
    
    if(getElementById('s1').innerHTML != getElementById('s2').innerHTML)
    { 
        alert(getElementById('s1').innerHTML);
        alert('total should be matched before proceed');
        return false();
    }
}
</script>
</HEAD>
<script type="text/javascript" src="tigra_hints.js"></script>   
<style>
    .hintsClass {            
    font-family: tahoma, verdana, arial;
    font-size: 12px;
    background-color: #f3ffff;
    color: #000000;
    border: 1px solid #808080;
    padding: 5px;
    }
    .hintSource {
    color: green;
    text-decoration: underline;
    cursor: pointer;  
    }
</style>
    <?
    $userid = $_SESSION['userid'];
    $sql="SELECT * from 0_ledger where group_id not in(1,7) and user_id = $userid";
    $result=mysql_query($sql)or die('Query error:'.''.mysql_errno());   
                         ?>
</head>
<body onload="startTime(); currentdate();">
<?php include_once('header.php');  
    include_once('menu3.php');?>
     <script language="JavaScript">

// configuration variable for the hint object, these setting will be shared among all hints created by this object
var HINTS_CFG = {
    'wise'       : true, // don't go off screen, don't overlap the object in the document
    'margin'     : 10, // minimum allowed distance between the hint and the window edge (negative values accepted)
    'gap'        : 0, // minimum allowed distance between the hint and the origin (negative values accepted)
    '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)
    'css'        : 'hintsClass', // a style class name for all hints, applied to DIV element (see style section in the header of the document)
    'show_delay' : 50, // a delay between initiating event (mouseover for example) and hint appearing
    'hide_delay' : 50, // a delay between closing event (mouseout for example) and hint disappearing
    'follow'     : false, // hint follows the mouse as it moves
    'z-index'    : 100, // a z-index for all hint layers
    'IEfix'      : false, // fix IE problem with windowed controls visible through hints (activate if select boxes are visible through the hints)
    'IEtrans'    : ['blendTrans(DURATION=.3)', 'blendTrans(DURATION=.3)'], // [show transition, hide transition] - nice transition effects, only work in IE5+
    'opacity'    : 100 // opacity of the hint in %%
}; 
// text/HTML of the hints
var HINTS_ITEMS = [
    'Date Should not be of Future',
    'If Last Actual Budget is Null then  it means no entry is passed in last month',
    'tooltip for item3This one is multi line',
    'tooltip for item4',
    'another sample tooltip with the <a href="http://www.softcomplex.com">link</a>'
];

var myHint = new THints(HINTS_ITEMS, HINTS_CFG);
</script>
<div class="clear">
</div>
<div id="menu2">
<ul>
    <li><a href="entry.php" style="font-family:Verdana, Arial, Helvetica, sans-serif; font-size:14px">Journal Entry</a></li>
    <li><a href="payment.php" style="font-family:Verdana, Arial, Helvetica, sans-serif; font-size:14px">Payments</a></li>
    <li><a href="deposit.php" style="font-family:Verdana, Arial, Helvetica, sans-serif; font-size:14px">Receipts</a></li>
    <li><a href="showgl.php" style="font-family:Verdana, Arial, Helvetica, sans-serif; font-size:14px">View Journal Entries </a></li>
    <li><a href="contra.php" style="font-family:Verdana, Arial, Helvetica, sans-serif; font-size:14px">Contra Entry</a></li>
</ul>
</div>
<div class="clear"></div>
<center>
    <table border="0" width="100%">
    <tr>
        <td width="20%"><font face="Courier New, Courier, mono" size="+1"><b>Journal Entry</b></font></td>
        <td align="center" width="50%"><b> Welcome&nbsp;&nbsp;<?= $_SESSION['username'];?></b></td>
        <td align="right"><div id="txt1"></div></td>    
    </tr>
    <tr>
        <td class="titletext" style="">&nbsp;</td>
        <td align="right" class="titletext" colspan="2">Time:<span id="txt"></span></td>
    </tr>
</table>
</center>
</center>
    <div class="clear"></div>
        <?include_once('msgbox.php'); ?>          


    <form method="post" name='testform' action="" onsubmit="return validate();">
<center>
    <table style="border-collapse: collapse;" width="50%" bgcolor="#f9f9f9" border="0" bordercolor="#cccccc" cellpadding="3" cellspacing="0">
    <input type="hidden" name='type' id='type' value="Journal">
            <tr>
                <td width="50%" align="right"><b>Date:</b></td>
                <td><input type="text" value="<?=$_POST['testinput']; ?>" name="testinput" readonly="readonly" onmouseover="myHint.show(0, this)"  onmouseout="myHint.hide()" />
                <script language="JavaScript">
                new tcal ({
                    // form name
                    'formname': 'testform',
                    // input name
                    'controlname': 'testinput'
                });
            
                </script>
            </a>
    </td>
            </tr>
    </table></center>
    <center>
    <table style="border-collapse: collapse;" id="tblSample" width="95%" bgcolor="#f9f9f9" border="1" bordercolor="#cccccc" cellpadding="3"    cellspacing="0" id="testtable">
    <tr>
        <td colspan="4"><center><span class="headingtext">Transactions</span></center></td>
    </tr>    
    <tr>
            <td class="tableheader">Account Description</td>
            <td class="tableheader">Debit</td>
            <td class="tableheader">Credit</td>
            <td class="tableheader">&nbsp;</td>
        </tr>
        <tr class="evenrow" id='tr3'>
            <td align="center">
            <select id="row[txt0][]" name="row[txt0][]" style="width:130px" onchange="return myPopup2();">    
            <? while($row=mysql_fetch_array($result)) { ?>
            <option value="<?=$row['ledger_id']?>"><?=$row['ledgerName'];?></option>
            <?}?>
            <option value="2">Add New Ledger</option> 
            </select> 
            </td>
<td><input type="text" name="row[txt1][]" onKeyUp="this.value=check(this.value); emptyStr(this.parentNode.parentNode)" onBlur="emptyStr(this.parentNode.parentNode)" ></td>
<td><input type="text" name="row[txt2][]" 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);sumus(); " disabled="true">   
<input type="button" value="del" onClick="ed(this); this.parentNode.parentNode.parentNode.deleteRow( this.parentNode.parentNode.rowIndex ); sumus();" disabled="true"></td>
</tr>
<tr>
<th>Total</th>
<td id="s1"></td>
<td id="s2"></td>
<td></td></tr></tbody></table>
</center>
</div><table align="center"><tbody><tr><td><b>Narration:</b></td>
        <td>
        <textarea  cols="40" rows="3" name="narration" id='narration'><?=$_POST['narration']?></textarea></td>
        </tr> <input type="hidden" name="counter" id="counter">
    </tbody>
</table>
</td>
</tr>
</tbody>
</table>
</center>
    <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">
</center>
</form>
</div><div id="footer">
<? include_once('footer.html'); ?>
</body>
</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

nish123
Junior Poster in Training
83 posts since Apr 2009
Reputation Points: 10
Solved Threads: 0
 

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 column, it cause me to change somewhat the other routine, but I hope you can find and understand.

To show the powerful dynamic fill I adopted the function knockOut() for to trim the option list at each 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.

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<HTML><HEAD>
<META http-equiv="content-type" content="text/html; charset=UTF-8">
<meta http-equiv="Content-Script-Type" content="text/javascript">
<TITLE>add/ed/del row</TITLE><?php  ?> <?php /*comments*/?>
<?php  
if($row=$_POST['row']) 
{ foreach($row as $k => $v)
  { foreach($v as $kk => $vv)
    { $wor[$kk][$k]=$vv;
    };
  };
} else $wor=""; 

$arrBrand=array(1=>"Electricity"
               ,2=>"Water"
               ,3=>"Gas"
               ,4=>"Appartement Rent"
               ,5=>"School Fee");
/** $arrayBrand can be get from a database
$res=mysql_query("SELECT distinct brand FROM table");
$i=0;while($cols = mysql_fetch_row($dbResult))
{$line[$i]="'$i':['$i++','".$cols[0]."']";
}
//*/
foreach($arrBrand as $kk => $vv){ $line[]="'$kk':['$kk','$vv']";}
$optOut="\n{".implode("\n,",$line)."}";
////oSel.length = 0;
?>
<script>
var i,d=document;
/*********************************************************************/
var oOpts = <?php print $optOut ?>; // move the set of Options into a JS object!

function add_option(what,where)     // to define and add one Option
{ var nop = d.createElement('option');
      nop.innerHTML = what[1];           // nop.text does not accept MSIE
      nop.value     = what[0];
      nop.title     = nop.alt = what[0]; // showes the option value as 'bubble'
      where.appendChild(nop);
}
function fill_sell(oSel,oSet,oExept) // to clear and fill back the Option set
{ if(oExept==undefined)oExept={};    // except used ones
  var myVal='';if(oSel.length>1){ myVal=oSel.value; oSel.length = 1; }
  for(var l in oSet)
  { if( (l==myVal) || !(l in oExept) ) add_option(oSet[l],oSel);
  } oSel.value=myVal;
}
function knockOut(formChild)   // to trim the each <select> option list
{ var selOpt=collect(formChild.form);
  var selAll = formChild.form.getElementsByTagName('select');
  var selNew = selAll[selAll.length-1];
  if(formChild.nodeName=='SELECT') selNew = formChild;
  for(i=0;i<selAll.length;i++) fill_sell(selAll[i], oOpts, collect(selAll[i].form));
}
function collect(frm)  // to create an object from all used values
{ var selVar = {};
  var selAll = frm.getElementsByTagName('select');
  for(var k=0;k < selAll.length ;k++)
  { if(selAll[k].length>1 && (selAll[k].value in oOpts)) selVar[selAll[k].value]=selAll[k].selectedIndex;
  } return selVar;
}
/**********************************************************************/

function add(oRow) 
{ oRow.parentNode.replaceChild(oRow.cloneNode(true ),oRow.parentNode.insertRow(oRow.rowIndex+1));
  var inpR = oRow.getElementsByTagName('input');
  var inpN = oRow.nextSibling.getElementsByTagName('input');
  var selR = oRow.getElementsByTagName('select')[0];
      selR.disabled=true;
  var selN = oRow.nextSibling.getElementsByTagName('select')[0];
      selN.length = 1;
  for(i=0;i<inpR.length;i++)
  { if(inpR[i].disabled)inpR[i].disabled=false;
    if(inpR[i].type=='text'){inpR[i].disabled=true;inpN[i].value=''};
    if(inpR[i].value=='add'){inpR[i].value='ed';inpN[i].disabled=true};
  } sumus();knockOut(selN);
}

function ed(oBut)
{ var nextSel = oBut.parentNode.parentNode.nextSibling.firstChild.firstChild;
  var trow = oBut.parentNode.parentNode;
  var inpR = trow.getElementsByTagName('input');
  var selR = trow.getElementsByTagName('select')[0];
  var addrow = trow.parentNode.childNodes[trow.parentNode.lastChild.rowIndex-1]
  var addeds = d.getElementsByName('added');
  for(i=0;i<inpR.length;i++)
  { if(oBut.value=='ed'   && inpR[i].type=='text'){inpR[i].disabled=false;selR.disabled=false;}
    if(oBut.value=='lock' && inpR[i].type=='text'){inpR[i].disabled=true; selR.disabled=true;}
  } 
  if(oBut.value=='ed')
  {  oBut.value='lock'
    for(i=0;i<addeds.length;i++)
	{ addeds[i].disabled=true;
	} oBut.disabled=false;
	addrow.childNodes[0].firstChild.disabled=true;
	addrow.childNodes[1].firstChild.disabled=true;
	addrow.childNodes[2].firstChild.disabled=true;
  } else // oBut.value is not 'lock'
  { oBut.value='ed'
    for(i=0;i<addeds.length;i++)
	{ addeds[i].disabled=false;
	} emptyStr(addeds[i-1].parentNode.parentNode)
	addrow.childNodes[0].firstChild.disabled=false;
	addrow.childNodes[1].firstChild.disabled=false;
	addrow.childNodes[2].firstChild.disabled=false;
  } knockOut(nextSel);
//alert(nextSel);
}
function send(oForm)
{ var inpF = oForm.getElementsByTagName('input');
  for(i=0;i<inpF.length;i++)
  { inpF[i].disabled=false;
  } oForm.submit();
} function check(strt){ return (/^\d*\.?\d*/.exec(strt)==strt)?strt:check(strt.slice(0,(strt.length-1))) }
function emptyStr(oRow)
{ var  oInpS   =oRow.getElementsByTagName('input');var sum1=0,sum2=0;
       oInpS[0].value=check(oInpS[0].value);   oInpS[1].value=check(oInpS[1].value);
  if(  oInpS[0].value &&  !(oInpS[1].value) || oInpS[1].value &&  !(oInpS[0].value))
       oInpS[2].disabled=false;
  else oInpS[2].disabled=true;
  sumus();
}
function sumus()
{ var sum1=0,sum2=0;
  var Col1InpS = d.getElementsByName('row[credit][]');
  var Col2InpS = d.getElementsByName('row[debet][]');
  for(i=0;i<Col1InpS.length;i++)
  { sum1+=1*Col1InpS[i].value;sum2+=1*Col2InpS[i].value;
  } d.getElementById('s1').innerHTML=sum1;d.getElementById('s2').innerHTML=sum2;
} 
</script>
</HEAD>
<BODY><form method="post" action="./fuj.php">
<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>
<input type="button" value="send" onClick="send(this.form)">
<script>fill_sell(d.getElementsByTagName('select')[0],oOpts)</script>
</form>
<?php print_r($_POST["row"]);print_r($wor);?>
</BODY>
</HTML>
sysel
Light Poster
49 posts since Jun 2009
Reputation Points: 11
Solved Threads: 3
 

This article has been dead for over three months

Post: Markdown Syntax: Formatting Help
You