Dynamic table along with value - php

JQUERY
<script type="text/javascript" src="jquery-1.5.1.min.js"></script>
<script type="text/javascript">
$('#aggiungi').live('click', function(){
var thisRow = $(this).parent().parent();
// clone and add data
thisRow.clone(true).insertAfter(thisRow).data('is_clone',true);
$(this).val("-");
$(this).attr("id","remove");
var nextRow = thisRow.next();
nextRow.find('input:not(#aggiungi)').val("");
if (thisRow.data('is_clone')){
while(thisRow.data('is_clone')){
thisRow = thisRow.prev();
}
}else{
nextRow.children(":first").remove();
}
currRowSpan = thisRow.children(":first").attr("rowspan");
thisRow.children(":first").attr("rowspan", currRowSpan+1);
});
$('#remove').live('click', function(){
var thisRow = $(this).parent().parent(),
prevRow = thisRow.prev();
if (thisRow.data('is_clone')){
while(prevRow.data('is_clone')){
prevRow = prevRow.prev();
}
}else{
prevRow = thisRow.next()
.removeData('is_clone')
.children(":first")
.before(thisRow.children(":first"))
.end();
}
currRowSpan = prevRow.children(":first").attr("rowspan");
prevRow.children(":first").attr("rowspan", currRowSpan-1);
thisRow.remove();
});
</script>
PHP
<form action="grading.php" method="post">
<table width-"100%" id="tableRealizzazione">
<tr>
<th></th>
<th style="padding:12px;text-align:center;">Personale</th>
<th style="padding:12px;text-align:center;">Percentage</th>
<th style="padding:12px;text-align:center;">Marketing point</th>
<th style="padding:12px;text-align:center;">Add/Remove</th>
</tr>';
echo '<tr class="even">
<td></td>
<td style="padding:12px;"><input type="text" value="" id="Personale" name="Personale"></td>
<td style="padding:12px;">
<input type="text" id="from" name="from" size="5%"> -
<input type="text" id="to" name="to" size="5%"> %
</td>
<td style="padding:12px;"><input type="text" class="totaliCostiGestione" id="marketpt" name="marketpt"></td>
<td style="padding:12px;"><input type="text" name="programid" value ="34" size="10%"></td>
<td style="padding:12px;"><input type="button" value="+" id="aggiungi"/></td>';
echo '</tr>';
echo '<tr><td><input type="submit" name="submit" value="submit"></td></tr>';
echo '</table>
</form>
When I fill the values of all text boxes and click submit, it prints only the last row and the the last row with value 34 not repeating for all the rest rows.
Here is my code in Fiddle
http://jsfiddle.net/gansai/PA9JF/

That is because you have to make arrays from your form:
eg:
<input type="text" id="from" name="from[]" size="5%"> -
to clone values you have to add:
newRow = thisRow.clone(true).insertAfter(thisRow).data('is_clone',true);
$(newRow+"[name^=programid]").val($(thisRow+"[name^=programid]").val());
Like this JSFiddle
then in PHP:
foreach($_POST['marketpt'] as $num => $val){
$Personale = $_POST[$num]['Personale'];
$from = $_POST[$num]['from'];
$to = $_POST[$num]['to'];
$marketpt = $_POST[$num]['marketpt'];
$programid = $_POST[$num]['programid'];
// process variables, eg: insert in database
}

Related

Autofill Input Field Based On Another Input Field OnKeyUp (Dynamic Generated)

I hope today I'll find good solution for my case below.
Case
Actually, I have dynamic input fields and let say there field A, B and C. So, the purpose is when field A receives OnKeyUp Action then field B and C will autofill based query result from field A value.
index.php
<html>
<body>
<script type="text/javascript">
var ct = 1;
// Function Tambah Form
function new_link()
{
ct++;
var div1 = document.createElement('div');
div1.id = ct;
// Link to Delete Form
var delLink = '<div style="text-align:left"><a id="del" href="javascript:delIt('+ ct +')">Delete</a></div>';
div1.innerHTML = document.getElementById('newlinktpl').innerHTML + delLink;
document.getElementById('newlink').appendChild(div1);
}
// Function Delete Form
function delIt(eleId)
{
d = document;
var ele = d.getElementById(eleId);
var parentEle = d.getElementById('newlink');
parentEle.removeChild(ele);
}
function ajaxFunction(str,divId)
{
var httpxml;
try
{
// Firefox, Opera 8.0+, Safari
httpxml=new XMLHttpRequest();
}
catch (e)
{
// Internet Explorer
try
{
httpxml=new ActiveXObject("Msxml2.XMLHTTP");
}
catch (e)
{
try
{
httpxml=new ActiveXObject("Microsoft.XMLHTTP");
}
catch (e)
{
alert("Your browser does not support AJAX!");
return false;
}
}
}
function stateChanged()
{
if(httpxml.readyState==4)
{
document.getElementById(divId).innerHTML=httpxml.responseText;
}
}
var url="cek.php";
url=url+"?txt="+str;
url=url+"&sid="+Math.random();
httpxml.onreadystatechange=stateChanged;
httpxml.open("GET",url,true);
httpxml.send(null);
}
</script>
</head>
<body>
<form name="myForm">
<a id="new" href="javascript:new_link()">ADD NEW PAYMENT</a>
<div id="newlink">
<table width="50%" border="1">
<tr>
<td><input type="text"
onkeyup="ajaxFunction(this.value,'displayDiv');" name="username" /></td>
<td>
<div id="displayDiv">
<table width="100%" border="0">
<tr>
<td><input type="text" name="curr"></td><td><input type="text" name="amount"></td>
</tr>
</table>
</div>
</td>
</tr>
</table>
</div>
</form>
</body>
</html>
<div id="newlinktpl" style="display:none" >
<div>
<table width="50%" border="1">
<tr>
<td><input type="text"
onkeyup="ajaxFunction(this.value,'displayDiv<?php echo ++$np;?>');" name="username" /></td>
<td>
<div id="displayDiv<?php echo $np;?>">
<table width="100%" border="0">
<tr>
<td><input type="text" name="curr"></td><td><input type="text" name="amount"></td>
</tr>
</table>
</div>
</td>
</tr>
</table>
</div>
</div>
cek.php
<?php
mssql_connect('localhost','sa','');
mssql_select_db('NCD');
$in=$_GET['txt'];
$msg="";
$t=mssql_query("SELECT * FROM DPaym1 WHERE (JENIS = 1) AND (DPSPAID = 0) AND (CNDPSNO = '$in')");
while($nt=mssql_fetch_array($t)){
//$msg = "$nt[CURRID]#$nt[AMOUNT]";
$curr = "$nt[CURRID]";
$amount = "$nt[AMOUNT]";
}
//echo $msg;
//echo "$curr $amount";
?>
<table width="100%" border="0">
<tr>
<td><input type="text" name="curr" value="<?php echo $curr?>"></td>
<td><input type="text" name="amount" value="<?php echo $amount?>"></td>
</tr>
</table>
Above code already success for row 1. but when I input value in row 2 (dynamic add new row) the result change field B and C in row 1 not in row 2.

Ajax php mysql - fetch multiple values

I want to fetch data from table 'driver' by using sql where (name = '? ') condition
and fill the result into three text boxes .
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
 <script language="JavaScript" type="text/javascript">
function ajax_post(){
// Create our XMLHttpRequest object
var hr = new XMLHttpRequest();
// Create some variables we need to send to our PHP file
var url = "my_parse_file.php";
var fn = document.getElementById("driver_name").value;
// var ln = document.getElementById("last_name").value;
var vars = "driver="+fn;
hr.open("POST", url, true);
// Set content type header information for sending url encoded variables in the request
hr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
// Access the onreadystatechange event for the XMLHttpRequest object
hr.onreadystatechange = function() {
if(hr.readyState == 4 && hr.status == 200) {
var return_data = hr.responseText;
document.getElementById("status").innerHTML = return_data;
document.getElementById("contact_no").value = return_data;
$("#wait").css("display","none");
}
}
// Send the data to PHP now... and wait for response to update the status div
hr.send(vars); // Actually execute the request
document.getElementById("status").innerHTML = "processing...";
$("#wait").css("display","block");
}
</script>
</head>
<body>
<form action="my_parse_file.php" method="post" id="form2">
<fieldset > <legend>Dispatch</legend>
<table width="50%" align="center">
<tr valign="baseline">
<td align="left">Dispatch_date:</td>
<td><input type="date" name="dispatch_date" value="" size="32" /></td>
</tr>
<tr valign="baseline">
<td align="left">Driver_name:</td>
<td><select name="driver_name" id="driver_name" onchange="javascript:ajax_post();">
<?php
do {
?>
<option value="<?php echo $row_drivers['Driver_Name']?>"><?php echo $row_drivers['Driver_Name']?></option>
<?php
} while ($row_drivers = mysql_fetch_assoc($drivers));
$rows = mysql_num_rows($drivers);
if($rows > 0) {
mysql_data_seek($drivers, 0);
$row_drivers = mysql_fetch_assoc($drivers);
}
?>
</select></td>
</tr>
<tr valign="baseline">
<td align="left">Driver_id:</td>
<td><input type="text" name="driver_id" value="" size="32" /></td>
</tr>
<tr valign="baseline">
<td align="left">Contact No.</td>
<td><input type="text" name="contact_no" id="contact_no" /></td>
</tr>
<tr valign="baseline">
<td align="left">Truck_id:</td>
<td><input type="text" name="truck_id" value="" size="32" /></td>
</tr>
<tr valign="baseline">
<td align="left">Nums. of skids</td>
<td><input type="number" min="0" max="30" id="skids" required="required" />
</td>
</tr>
<tr valign="baseline">
<td align="left"> </td>
<td><input type="submit" value="Insert record" />
<?php ?></td>
</tr>
</table>
</fieldset>
<input type="hidden" name="MM_insert" value="form2" />
</form>
I am trying to fetch data from other php page
<?php echo ' Driver Name' ?>
<?php echo ' Driver ID' ?>
<?php echo ' Contact no' ?>
so please help I am just new to Ajax and php
Encode the output of the PHP file you're fetching with AJAX as JSON using json_encode and then parse hr.responseText as JSON and access the data accordingly.
Have a look here: http://www.json.org/js.html

How to call javascript function on multiple checkbox click in php?

How to call javascript function on multiple checkbox click in php?
When i am downloading excel its not fetching the selected values.
<script>
function xls_fun()
{
alert('hi');
var code=document.getElementById('code').value;
var hpnm=document.getElementById('hpnm').value;
var d_add=document.getElementById('d_add').value;
document.getElementById('xls_link').href="createxls.php?fnm=mynewxls.xls&code="+code+"&hpnm="+hpnm+"&d_add="+d_add+"&placeValuesBeforeTB_=savedValues&TB_iframe=true&height=100&width=150&modal=false";
}
</script>
<tr><th align="center">Code Number</th><th align="center">Name Of Hospital</th>
<th align="center">Doctor Address</th></tr>
<tr><td><?php echo $row1['code'];?></td><td><?php echo $row1['hname'];?></td>
<td><?php echo $row1['doc_add'];?></td></tr>
<tr><th align="center"><th align="center"><input type="checkbox" name="code" id="code" value="<?php echo $row1['code'];?>" onchange="xls_fun()"></th>
<th align="center"><input type="checkbox" name="hpnm" id="hpnm" value="<?php echo $row1['hname'];?>" onchange="xls_fun()"></th>
<th align="center"><input type="checkbox" name="d_add" id="d_add" value="<?php echo $row1['doc_add'];?>" onchange="xls_fun()"></th>
<script>
function checkall(objForm)
{
len = objForm.elements.length;
var i=0;
for( i=0 ; i<len ; i++){
if (objForm.elements[i].type=='checkbox')
objForm.elements[i].checked=objForm.check_all.checked;
}
frmobj.what.value="Delete";
frmobj.action = "books/delete";
frmobj.submit();
}
</script>
<th><input name="check_all" type="checkbox" id="check_all" onclick="checkall(this.form)" value="check_all" /></th>
Hope this will help you :)

Javascript define getElementById() from php variable?

I have a shipping module I'm trying to update. I'd like to be able to add rows for each line item in my php form/table. What ends up happening is the add/delete row buttons show up for each line item as desired but only affect the first line item. If I add a row to line item 1 it adds a row properly. But if I go to add a row for line item 2 it actually adds a row for line item 1 as well. If I try to add a row for line item 3 it again adds a line for item 1. I want to be able to add rows for each item.
I have a while loop in php that calls a javascript function. Problem is that one of the variables in the javascript requires an ID. Despite going through my loop the ID never changes and therefore my javascript only applies to a single loop which is not my desired output. I'm thinking if I can have the javascript receive a variable from PHP that contains my ID I can get the javascript to run for each pass through my loop.
Here is my javascript:
<SCRIPT language="javascript">
// Last updated 2006-02-21
function addRowToTable()
{
var tbl = document.getElementById('tblSample');
var lastRow = tbl.rows.length;
// if there's no header row in the table, then iteration = lastRow + 1
var iteration = lastRow + 1;
var row = tbl.insertRow(lastRow);
// Item cell
var cellLeft = row.insertCell(0);
var textNode = document.createTextNode(iteration);
cellLeft.appendChild(textNode);
// Cust PN cell
var cellBox_Num = row.insertCell(1);
var el = document.createElement('input');
el.type = 'text';
el.name = 'Box_Num[]';
el.id = 'Box_Num' + iteration;
el.size = 18;
el.onkeypress = keyPressTest;
cellBox_Num.appendChild(el);
}
function keyPressTest(e, obj)
{
var validateChkb = document.getElementById('chkValidateOnKeyPress');
if (validateChkb.checked) {
var displayObj = document.getElementById('spanOutput');
var key;
if(window.event) {
key = window.event.keyCode;
}
else if(e.which) {
key = e.which;
}
var objId;
if (obj != null) {
objId = obj.id;
} else {
objId = this.id;
}
displayObj.innerHTML = objId + ' : ' + String.fromCharCode(key);
}
}
function removeRowFromTable()
{
var tbl = document.getElementById('tblSample');
var lastRow = tbl.rows.length;
if (lastRow > 1) tbl.deleteRow(lastRow - 1);
}
</SCRIPT>
Here is my loop:
<?php
$i=0;
$n=1;
while($i < $num1) {
$SO_Line_Item=mysql_result($result1,$i,"SO_Line_Item");
$Cust_PN=mysql_result($result1,$i,"Cust_PN");
$Cust_PN_Rev=mysql_result($result1,$i,"Cust_PN_Rev");
$Description=mysql_result($result1,$i,"Description");
$SOItemQty=mysql_result($result1,$i,"Qty");
$UOM=mysql_result($result1,$i,"UOM");
$Program=mysql_result($result1,$i,"Program");
$Required_Date=mysql_result($result1,$i,"Required_Date");
$SOItemShipQty=mysql_result($result2,$i,"count(E9_SN)");
?>
<tr>
<td width="3px" valign="top" align="center"><?php
echo "$SO_Line_Item";?>
</td>
<td nowrap="nowrap" valign="top" align="center"><?php
echo "$Cust_PN - $Cust_PN_Rev";?>
</td>
<td nowrap="nowrap" valign="top" align="center"><?php
echo "$Description";?>
</td>
<td nowrap="nowrap" valign="top" align="center">
<?php
echo "$SOItemQty";?>
</td>
<td nowrap="nowrap" valign="top" align="center">
<?php
echo "$UOM";?>
</td>
<td nowrap="nowrap" valign="top" align="center">
<?php
echo $SOItemQty - $SOItemShipQty;?>
</td>
<td nowrap="nowrap" valign="top" align="center">
<input size="2" align="right" type="text" name="Qty">
</td>
<td nowrap="nowrap" valign="top" align="center">
<?php
echo "$Required_Date";?>
</td>
<td nowrap="nowrap" valign="top" align="center">
<?php
echo "$Program";?>
</td>
</tr>
//HERE IS WHERE THINGS GO SOUTH. I'd LIKE TO BE ABLE TO ADD A LINE FOR EACH PART
//NUMBER... WHAT HAPPENS IS THIS IS ALWAYS RUN FOR THE SAME ID AND WHILE THE FORM
//DISPLAYS PROPERLY THE ADD AND DELETE ALWAYS MODIFY THE FIRST PART
<tr>
<td colspan="10">
<p>
<input type="button" value="Add" onclick="addRowToTable();" />
<input type="button" value="Remove" onclick="removeRowFromTable();" />
<!--
<input type="button" value="Submit" onclick="validateRow(this.form);" />
<input type="checkbox" id="chkValidate" /> Validate Submit
-->
<b><font color="RED">Add/Remove Box Number For This Line Item</font></b>
</p>
</td>
</tr>
<tr>
<td></td>
<td>
<table id="tblSample">
<tr>
<td>1</td>
<td><input type="text" name="Box_Num[]"
id="Box_Num1" size="18" onkeypress="keyPressTest(event, this);" /></td>
</tr>
</table>
</td>
</tr>
<?php
$i++;
}
Thanks in advance!
Simply pass a table id into your row addition and deleletion javascript functions. You could change the first couple line of both function to be like this:
function addRowToTable(tableID)
{
var tbl = document.getElementById('tblSample_' + tableID);
...
}
You would also use your PHP counter to pass the table counter value to the javascript functions like this
<input type="button" value="Add" onclick="addRowToTable('<?php echo $i; ?>');" />
<input type="button" value="Remove" onclick="removeRowFromTable('<?php echo $i; ?>');" />
and add the counter to the table id's like this.
<table id="tblSample_<?php echo $i; ?>">

How to sum the input field values and display it into html Table using Javascript?

I am new to Javascript, Please help to me solve this issue Javascript experts.
I have a registration form that have these above fields. In this form, When I click "Add new registration line", it will insert new insert field like as above. From these, I want to add these hightlighted input fields values and display it in html table. When I check the checkbox, the values should be displayed in invoicable field, Likewise when I uncheck the checkbox, the values should be displayed in Non-Voicable field. I mean the sum of checked values should be displayed in Invoicable field and the sum of unchecked values should be displayed in Non-invoicable field.
This is the code part of the issue i am trying:
<script type="text/javascript">
$(function() {
var i = 8 + 1;
$('input#add').click(function() {
//store in hidden value for total row
document.getElementById("consinvoice").value=i;
$("<span style='margin-left:126px;'>: <select name='RegistrationType_"+i+"' id='RegistrationType_"+i+"' onchange=\"register('Invoicable_"+i+"',this.value,ConsultancyHours_"+i+".value)\"><option value='CH'>Consultancy Hours</option><option value='LH'>Lunch Hours</option><option value='TH'>Transportation Hours</option><option value='OH'>Other Hours</option></select> <input name='ConsultancyHours_"+i+"' type='text' id='ConsultancyHours_"+i+"' size='5' onkeyup=\"invotable(this.id,this.value);\" /><label for='Hourprice'> Std. Hourprice</label> <input name='Hourprice_"+i+"' type='text' id='Hourprice_"+i+"' size='5' /> <label for='Hourprice'>- Discount Hourprice</label> <input name='Hourprice2_"+i+"' type='text' id='Hourprice2_"+i+"' size='5' /><br /><span style='margin-left:652px;'><input name='Invoicable_"+i+"' type='checkbox' id='Invoicable_"+i+"' checked='checked' onclick=\"register('Invoicable_"+i+"',RegistrationType_"+i+".value,ConsultancyHours_"+i+".value)\" /><label for='Invoicable'> Invoicable</label></span><br /></span>").appendTo('dd');
i++;
});
});
</script>
<script type="text/javascript">
//register('Invoicable_"+i+"',RegistrationType_"+i+".value,this.value);
function invotable(getid,getvalue){
var getinvoicetbl = 'invoice_cons';
var previnvoice = document.getElementById(getinvoicetbl).innerHTML;
var dgetid = getid.split("_");
var getcount = document.getElementById("consinvoice").value;
//alert(getcount);
totalterm =0;
for (j=8;j<=getcount;j++)
{
totalterm += parseInt(document.getElementById("ConsultancyHours_"+j).value);
//register('Invoicable_'+j,document.getElementById("RegistrationType_"+j).value,document.getElementById("ConsultancyHours_"+j).value);
}
document.getElementById(getinvoicetbl).innerHTML = totalterm;
}
function register(getvoice,gettype,getvalue){
//alert(getvoice);
var checkbox = document.getElementById(getvoice).checked;
var getinvoice = 'invoice_cons';
var getnovoice = 'ninvoice_cons';
switch (gettype)
{
case "CH":
if(checkbox ==true){
//alert("true");
document.getElementById(getinvoice).innerHTML = parseInt(document.getElementById("invoice_cons").innerHTML)+parseInt(getvalue);
document.getElementById("totinvoice").value = document.getElementById(getinvoice).innerHTML;
document.getElementById(getnovoice).innerHTML = document.getElementById("totinvoice").value - getvalue;
alert(document.getElementById("totinvoice").value);
alert(document.getElementById(getnovoice).innerHTML);
} else {
alert(document.getElementById("totinvoice").value);
document.getElementById(getnovoice).innerHTML = parseInt(getvalue);
document.getElementById("totinvoice").value = document.getElementById(getnovoice).innerHTML;
document.getElementById(getinvoice).innerHTML = document.getElementById("invoice_cons").innerHTML - getvalue;
}
break;
case "LH":
if(checkbox ==true ){
//alert("true");
document.getElementById(getinvoice).innerHTML = parseInt(document.getElementById("invoice_cons").innerHTML)+parseInt(getvalue);
document.getElementById("totinvoice").value = document.getElementById(getinvoice).innerHTML;
document.getElementById(getnovoice).innerHTML = document.getElementById("invoice_cons").innerHTML - getvalue;
} else {
document.getElementById(getnovoice).innerHTML = parseInt(document.getElementById("invoice_cons").value)+parseInt(getvalue);
document.getElementById("totinvoice").value = document.getElementById(getnovoice).innerHTML;
document.getElementById(getinvoice).innerHTML = document.getElementById("invoice_cons").innerHTML - getvalue;
}
default:
if(checkbox ==true){
//alert("true");
document.getElementById(getinvoice).innerHTML = parseInt(document.getElementById("invoice_cons").innerHTML)+parseInt(getvalue);
document.getElementById("totinvoice").value = document.getElementById(getinvoice).innerHTML;
document.getElementById(getnovoice).innerHTML = document.getElementById("invoice_cons").innerHTML - getvalue;
} else {
document.getElementById(getnovoice).innerHTML = parseInt(document.getElementById("invoice_cons").value)+parseInt(getvalue);
document.getElementById("totinvoice").value = document.getElementById(getnovoice).innerHTML;
document.getElementById(getinvoice).innerHTML = document.getElementById("invoice_cons").innerHTML - getvalue;
}
}
}
</script>
<input type="hidden" name="consinvoice" id="consinvoice" value="8" />
<input type="hidden" name="totinvoice" id="totinvoice" value="0" />
<input type="hidden" name="fromtinvoice" id="fromtinvoice" value="0" />
<td width="220">
<span id="insert_table">
<table class="" id="invtable" width="150" border="1">
<tr>
<td align="right">
</td>
<td align="right" style="padding-left:15px; padding-bottom:10px;">
Invoicable
</td>
<td align="right" style="padding-left:15px; padding-bottom:10px;">
Non-Invoicable
</td>
<td align="right" style="padding-left:15px; padding-bottom:10px;">
Total
</td>
</tr>
<tr>
<td style="padding-bottom:10px;">Consultancy</td>
<td align="right" id="invoice_cons">-</td>
<td align="right" id="ninvoice_cons">-</td>
<td align="right" >-</td>
</tr>
<tr>
<td style="padding-bottom:10px;">Transportation</td>
<td align="right" id="invoice_trans">-</td>
<td align="right" id="ninvoice_trans">-</td>
<td align="right" >-</td>
</tr>
<tr>
<td style="padding-bottom:10px;">Lunch</td>
<td align="right" id="invoice_lun">-</td>
<td align="right" id="ninvoice_lun">-</td>
<td align="right" >-</td>
</tr>
<tr>
<td style="padding-bottom:10px;">Total</td>
<td align="right" id="invoice_tot">-</td>
<td align="right" id="ninvoice_tot">-</td>
<td align="right" >-</td>
</tr>
<tr>
</table>
</span>
</table>
<p>
<label for="RegistrationType">
Type
</label>
<span style="margin-left:92px;">
: <select name="RegistrationType_8" id="RegistrationType_8" onchange="register('Invoicable_8',this.value,ConsultancyHours_8.value)">
<option value="CH">Consultancy Hours</option>
<option value="LH">Lunch Hours</option>
<option value="TH">Transportation Hours</option>
<option value="OH">Other Hours</option>
</select>
<input name="ConsultancyHours_8" type="text" id="ConsultancyHours_8" size="5" onkeyup="invotable(this.id,this.value); " />
<label for="Hourprice">
Std. Hourprice
</label>
<input name="Hourprice_8" type="text" id="Hourprice_8" size="5" />
<label for="Hourprice">
- Discount Hourprice
</label>
<input name="Hourprice2_8" type="text" id="Hourprice2_8" size="5" />
<input name="Invoicable_8" type="checkbox" id="Invoicable_8" onclick="register('Invoicable_8',RegistrationType_8.value,ConsultancyHours_8.value)" checked="checked" />
<label for="Invoicable">
Invoicable
</label>
<dd id="insert_row">
</dd>
</span>
</p>
<p>
<span style="margin-left:132px;">
<input type="button" id="add" value="Add new registration line" />
</span>
</p>
<div style="margin-left:324px;">
</div>
<br />
<p>
<span style="margin-left:132px;">
<input type="submit" name="Submit" id="Submit" value="Save registration" />
</span>
</p>
You can create a function to add new row dynamically and other function to calculate the hour by scaning the form, then when the window is loaded, call the add row function to start. There is the source code that I created:
<!DOCTYPE html>
<style>
body{margin:0}
body,th,td{font:16px Arial, Helvetica, sans-serif}
table{border-spacing:0;border-collapse:collapse;table-layout:fixed}
th,td{white-space:nowrap;overflow:hidden}
th{font-weight:700}
#invtable{width:500px;margin:10px auto;border:1px solid #000}
#invtable th, #invtable td{border:1px solid #000}
#registrationForm{width:100%}
#registrationForm td{text-align:center}
#registrationForm input[type="number"]{width:140px}
</style>
<table id="invtable" width="150">
<tr>
<th>Type</th>
<th>Invoicable</th>
<th>Non-Invoicable</th>
<th>Total</th>
</tr>
<tr id="consultancy">
<th>Consultancy</th>
<td>0</td>
<td>0</td>
<td>0</td>
</tr>
<tr id="transportation">
<th>Transportation</th>
<td>0</td>
<td>0</td>
<td>0</td>
</tr>
<tr id="lunch">
<th>Lunch</th>
<td>0</td>
<td>0</td>
<td>0</td>
</tr>
<tr id="other">
<th>Other</th>
<td>0</td>
<td>0</td>
<td>0</td>
</tr>
<tr id="total">
<th>Total</th>
<td>0</td>
<td>0</td>
<td>0</td>
</tr>
</table>
<table id="registrationForm"></table>
<p><input type="button" id="addNewRegistrationLine" value="Add new registration line"></p>
<p><input type="submit" id="saveRegistration" value="Save registration"></p>
<script>
var doc = document;
function calculateHour() {
var registrationForm = doc.getElementById('registrationForm');
var registrationFormRows = registrationForm.rows
var typeValue = {'CH' : [0,0], 'LH' : [0,0], 'TH' : [0,0], 'OH' : [0,0]};
for (var i = 0, registrationFormRowsLength = registrationFormRows.length, typeSelect, inputs, hourInput, isInvoicable; i < registrationFormRowsLength; ++i) {
typeSelect = registrationFormRows[i].getElementsByTagName('SELECT')[0];
inputs = registrationFormRows[i].getElementsByTagName('INPUT');
hourInput = inputs[0];
isInvoicable = inputs[inputs.length - 1].checked ? 0 : 1;
typeValue[typeSelect.value][isInvoicable] += hourInput.value - 0;
}
var total = [0, 0]
var consultancyCells = doc.getElementById('consultancy').cells;
consultancyCells[1].innerHTML = typeValue['CH'][0];
total[0] += typeValue['CH'][0];
consultancyCells[2].innerHTML = typeValue['CH'][1];
total[1] += typeValue['CH'][1];
consultancyCells[3].innerHTML = typeValue['CH'][0] + typeValue['CH'][1];
var transportationCells = doc.getElementById('transportation').cells;
transportationCells[1].innerHTML = typeValue['TH'][0];
total[0] += typeValue['TH'][0];
transportationCells[2].innerHTML = typeValue['TH'][1];
total[1] += typeValue['TH'][1];
transportationCells[3].innerHTML = typeValue['TH'][0] + typeValue['TH'][1];
var lunchCells = doc.getElementById('lunch').cells;
lunchCells[1].innerHTML = typeValue['LH'][0];
total[0] += typeValue['LH'][0];
lunchCells[2].innerHTML = typeValue['LH'][1];
total[1] += typeValue['LH'][1];
lunchCells[3].innerHTML = typeValue['LH'][0] + typeValue['LH'][1];
var otherCells = doc.getElementById('other').cells;
otherCells[1].innerHTML = typeValue['OH'][0];
total[0] += typeValue['OH'][0];
otherCells[2].innerHTML = typeValue['OH'][1];
total[1] += typeValue['OH'][1];
otherCells[3].innerHTML = typeValue['OH'][0] + typeValue['OH'][1];
var totalCells = doc.getElementById('total').cells;
totalCells[1].innerHTML = total[0];
totalCells[2].innerHTML = total[1];
totalCells[3].innerHTML = total[0] + total[1];
}
function addNewRegistrationLine() {
var registrationForm = doc.getElementById('registrationForm');
var row = registrationForm.insertRow(registrationForm.rows.length);
var typeSelectCell = row.insertCell(0);
var type = [['CH', 'Consultancy Hours'], ['LH', 'Lunch Hours'], ['TH', 'Transportation Hours'], ['OH', 'Other Hours']];
var typeSelect = doc.createElement('SELECT');
for (var i = 0, typeLength = type.length, option; i < typeLength; ++i) {
option = doc.createElement('OPTION');
option.value = type[i][0];
option.innerHTML = type[i][1];
typeSelect.appendChild(option);
}
typeSelect.onchange = calculateHour;
var typeLabel = doc.createElement('LABEL');
typeLabel.innerHTML = 'Type';
typeLabel.appendChild(typeSelect);
typeSelectCell.appendChild(typeLabel);
var hourInput = doc.createElement('INPUT');
hourInput.type = 'number';
hourInput.onkeyup = calculateHour;
typeSelectCell.appendChild(hourInput);
var hourPriceInputCell = row.insertCell(1);
var hourPriceInput = doc.createElement('INPUT');
hourPriceInput.type = 'number';
var hourPriceLabel = doc.createElement('LABEL');
hourPriceLabel.innerHTML = 'Std. Hourprice';
hourPriceLabel.appendChild(hourPriceInput);
hourPriceInputCell.appendChild(hourPriceLabel);
var discountInputCell = row.insertCell(2);
var discountInput = doc.createElement('INPUT');
discountInput.type = 'number';
var discountLabel = doc.createElement('LABEL');
discountLabel.innerHTML = '- Discount Hourprice';
discountLabel.appendChild(discountInput);
discountInputCell.appendChild(discountLabel);
var invoicableCheckBoxCell = row.insertCell(3);
var invoicableCheckBox = doc.createElement('INPUT');
invoicableCheckBox.type = 'checkbox';
invoicableCheckBox.onclick = calculateHour;
var invoicableLabel = doc.createElement('LABEL');
invoicableLabel.appendChild(invoicableCheckBox);
invoicableLabel.appendChild(document.createTextNode('Invoicable');
invoicableCheckBoxCell.appendChild(invoicableLabel);
}
doc.getElementById('addNewRegistrationLine').onclick = addNewRegistrationLine;
window.onload = function() {
addNewRegistrationLine();
};
</script>
Live example
since it appears that you are using the Jquery Framework you can use the template feature which will allow you to use your javascript data and create html from it, I personally have not used it though.But since you also tagged this with PHP. Why not just do it in PHP?
For Example:
$formData[];
foreach($_POST AS $field => $value) {
$formData[$field] = $value;
}
Then all your data is in an array and much easier to work with. Just make sure to put in the form tag and use the method=“post” attribute.

Categories