Javascript define getElementById() from php variable? - php

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; ?>">

Related

increment variable on submit to update mysql query

I am new to PHP(loving it already)
I have a form that looks up a table that sends 'golf hole' info back and allows a golfer to input their score of the hole. Problem I have is that I can present the first hole by looking up the hole_detail table but then cant figure out how loop through the table for hole 2, 3.....18 when the form is submitted. I have searched stackoverflow but cant find anything that specific about it. I have tried an if statement, if (isset($_POST['Submit'])) to try increment the $hole_id. Am I completely going about it the wrong way? Thanks in advance.
<?php
include ('../scripts/dbconfig.php');
# get the most recent course name:
$get_course_name = mysql_query("SELECT course_name FROM comp ORDER BY PID DESC LIMIT 1");
$show_course_name = mysql_fetch_array($get_course_name);
if (isset($_POST['Submit'])) {
$hole_id =1;
else {
$hole_id = $hole_id + 1;
}
}
# get the hole yardage and SI from most recent selected golf course:
$get_course_detail = mysql_query("SELECT * FROM `course_detail` WHERE course_name = '". $show_course_name['course_name'] . "'");
$show_course_detail = mysql_fetch_array($get_course_detail);
$get_hole_detail = mysql_query("SELECT * FROM `course_detail`,`phoenix_hole` WHERE Course_ID = 6 AND hole_id = $hole_id");
$show_hole_detail = mysql_fetch_array($get_hole_detail);
?>
</head>
<body>
<table width="300" cellspacing="0" cellpadding="0">
<tr>
<td width="40"><?php echo $show_course_name['course_name'];?></td>
</tr>
<tr>
<td width="20">HOLE <?php echo $show_hole_detail['hole_id']?></td>
<td width="5"> PAR <?php echo $show_hole_detail['hole_par'];?></td>
</tr>
<tr>
<td width="20">Yards</td>
<td width="20">S.I</td>
</tr>
<tr>
<td bgcolor="yellow"><?php echo $show_hole_detail['yellow_yards'];?></td>
<td><?php echo $show_hole_detail['hole_si'];?></td>
</tr>
<tr>
<td border="1px" bgcolor="white"><?php echo $show_hole_detail['white_yards'];?></td>
<td><?php echo $show_hole_detail['hole_si'];?></td>
</tr>
<tr>
<td bgcolor="red"><?php echo $show_hole_detail['red_yards'];?></td>
<td><?php echo $show_hole_detail['hole_si'];?></td>
</tr>
</table>
</p>
<form id="game_form" name="game_form" method="post" action="game_form.php">
<table width="300" border="0" align="left" cellpadding="2" cellspacing="0">
<tr>
<td><b>Hole Shots</b></td>
<td><input name="hole_shots" type="text" class="textfield" id="hole_shots" maxlength="2" size="3" ></td>
<td><b>Putts</b></td>
<td><input name="putts" type="text" class="textfield" id="putts" maxlength="2" size="3"></td>
</tr>
<tr>
<td> </td>
<td><input type="submit" name="Submit" value="Next Hole" align="center" /></td>
</tr>
</table>
</form>
</body>
</html>
Or you can use a hidden field that keeps the hole number and you can increment it from php.
$hole_id, in this scenario, will always be 1, because when a user clicks the Submit button, $_POST['Submit'] will always have a value. What you should do instead is have $_POST['Submit'] contain the value of $hole + 1. PHP is not going to "remember" what $hole_id was last time around; it's up to you to remind it. As soon as a request is sent to the browser--unless you're using sessions--PHP forgets everything about that request (HTTP is "stateless").
<?php
if (isset($_POST['Submit'])) {
$hole_id = (int)$_POST['Submit'];
} else {
$hole_id = 1;
}
# other code here
?>
You are on hole #<?php echo $hole_id; ?>.
<form>
<!-- form stuff here -->
<button type="submit" name="Submit" value="<?php echo $hole_id + 1; ?>">Next hole</button>
</form>

Using PHP and Javascript in onblur function

so I have this form:
<form enctype="multipart/form-data" action="cgi-bin/upload.cgi?upload_id=" method="post" onSubmit="return StartUpload(this);" target="xupload">
<table>
<tr>
<td class="first"><span class="right">Upload File: </span></td>
<td class="second"><input name="file_1" type="file" onChange="checkExt(this.value)" accept=".mp4, .avi, .wmv, .mov, .camrec, .flv, .zip, .rar"></td>
<td class="third"><span class="left">(required)</span></td>
</tr>
<tr></tr>
<tr><center><h2>Video Information</h2></center></tr>
<tr></tr>
<tr>
<td class="first"><span class="right">Your Name: </span></td>
<td class="second"><input type="text" name="name"></td>
<td class="third"><span class="left">(preferred)</span></td>
</tr>
<tr>
<td class="first"><span class="right">Series ID: </span></td>
<td class="second"><input id="series_id" type="text" name="series_id" placeholder="You should have been given this by your admin"></td>
<td class="third"><span class="left">(preferred)</span></td>
</tr>
<tr>
<td class="first"></td>
<td class="second"><span id="series_id_check">Enter You're series ID Above and this will change</span></td>
<td class="third"></td>
</tr>
<tr>
<td class="first"><span class="right">Title: </span></td>
<td class="second"><input type="text" name="title"></td>
<td class="third"><span class="left">(preferred)</span></td>
</tr>
<tr>
<td class="first"></td>
<td class="second center"><small>Please use "<span style="color:#9c0000"><br></span>" to make a new line</small></td>
<td class="third"></td>
</tr>
<tr>
<td class="first"><span class="right">Description: </span></td>
<td class="second"><textarea name="desc"></textarea></td>
<td class="third"><span class="left">(preferred)</span></td>
</tr>
<tr>
<td class="first"><span class="right">Guests: </span></td>
<td class="second"><input type="text" name="guests"></td>
<td class="third"><span class="left">(optional)</span></td>
</tr>
<tr>
<td class="first"><span class="right">Additional Tags: </span></td>
<td class="second"><input type="text" name="tags"></td>
<td class="third"><span class="left">(comma separated - optional)</span></td>
</tr>
</table>
<input type="submit" name="submit" value="Upload File">
</form>
Which I use to upload videos to my web hosting server. I want to be able to change the text in the series_id_check span with some javascript that uses PHP arrays... Here's the PHP that I use for populating the arrays from mysql (I KNOW THAT ITS DEPRECIATED BUT FOR MY WEB HOSTING PHP 5.3 IS INSTALLED AND ITS ONLY DEPRECIATED FROM 5.4):
$sql1 = mysql_fetch_assoc(mysql_query("SELECT COUNT cnt FROM series"));
$count = $sql1['cnt'];
$gamearray = array($count - 1);
$namearray = array($count - 1);
$idarray = array($count - 1);
for ($i = 0; $i < $count; $i++)
{
$sql2 = mysql_fetch_assoc(mysql_query("SELECT id,game,name FROM series WHERE id='{$i}'"));
$gamearray[$i] = $sql2['game'];
$namearray[$i] = $sql2['name'];
$idarray[$i] = $sql2['id'];
}
I know it connects to the database fine as I've got a die statement when it tries to connect
The javascript is:
var id = "series_id";
document.getElementById("series_id").onblur = function()
{
var value = document.getElementById(id).value;
var gameArray = new Array(<? echo implode(',', $gamearray); ?>;
var nameArray = new Array(<? echo implode(',', $namearray); ?>;
var idArray = new Array(<? echo implode(',', $idarray); ?>;
if (inArray(value,idArray)
{
var id = parceInt(value);
var game = gameArray.indexOf(id);
var name = nameArray.indexOf(id);
var input= "You've inputted the id for the game: " + game + " for the series: " + name;
document.getElementById("spawn_series_id_check").innerHTML = input;
}
});
function inArray(var input, var array)
{
var count = array.length;
var returnVal = false;
for (var i = 0; i < count; i++)
{
if (array[i] == input)
{
returnVal = true;
}
}
return returnVal;
}
Basically the text in the series_id_check doesn't change. Could you tell me how to fix it
You should consider using JSON to handle these data.
$result = mysql_query("SELECT id,game,name FROM series");
$count = count($result);
$series = array();
while ($row = mysql_fetch_assoc($result)) {
$series[$row['id']] = array('game' => $row['game'], 'name' => $row['name']);
}
And at your JS:
document.getElementById("series_id").onblur = function()
{
var series = '<?php echo json_encode($series); ?>';
var id = parseInt(this.value, 10);
if (undefined !== series[id])
{
var game = series[id]['game'];
var name = series[id]['name'];
var message = "You've inputted the id for the game: " + game + " for the series: " + name;
document.getElementById("spawn_series_id_check").innerHTML = message;
}
});
I haven't tested the code, but this is the way you should go.
Your javascript arrays are incomplete, and will come out like this:
var gameArray = new Array(-1;
try rewriting the array building part of you code to do this for each array:
var gameArray = new Array(<? echo implode(',', $gamearray); ?>);
Notice that the javascript array and line has been closed.
added fix
if (inArray(value,idArray)
{
should be
if (inArray(value,idArray))
{
And another - try changing
function inArray(var input, var array)
{
to
function inArray(input, array)
{
Also - cannot set property of null likley means an issue with the anonymous function.
The second line of your function var value = document.getElementById(id).value
needs to end with a semicolon var value = document.getElementById(id).value;

Javascript add MySQL data when checkbox is ticked

I am currently using this javscript and PHP code
<script>
function add(total)
{
form2.thetotal.value = document.forms["form1" + total].total.value;
}
</script>
<form name="form2">
<table width="800" border="0" cellspacing="0" cellpadding="10" style="position:fixed; z-index:-999; background-color:#FFF;">
<tr bgcolor="#eeeeee">
<td> </td>
<td colspan="2" width="50%"><strong>Total: </strong><input type="text" name="thetotal" id="thetotal" size="20" value="0" /></td>
<td colspan="2" width="50%"><strong>VAT:</strong> </td>
</tr>
<tr bgcolor="#eeeeee">
<td width="5%"> </td>
<td width="20%"><strong>Invoice Number</strong></td>
<td width="35%"><strong>Company</strong></td>
<td width="20%"><strong>Date</strong></td>
<td width="20%"><strong>Total</strong></td>
</tr>
</table>
</form>
<form name="form1">
<table width="800" border="0" cellspacing="0" cellpadding="10">
<?php
$sql="SELECT * from billing_pdf_archive order by invoice_number ASC ";
$rs=mysql_query($sql,$conn) or die(mysql_error());
while($result=mysql_fetch_array($rs))
{
$counter++;
$sql2="SELECT * from customer where sequence = '".$result["customer_sequence"]."' ";
$rs2=mysql_query($sql2,$conn) or die(mysql_error());
$result2=mysql_fetch_array($rs2);
$sql3="SELECT * from reseller where sequence = '".$result["reseller_sequence"]."' ";
$rs3=mysql_query($sql3,$conn) or die(mysql_error());
$result3=mysql_fetch_array($rs3);
if($result["customer_sequence"] != '0')
{
$company = $result2["company"];
}
elseif($result["reseller_sequence"] != '0')
{
$company = '<strong>Reseller: </strong>'.$result3["company"];
}
$total = $result["total"];
echo '<tr>
<td width="5%"><input type="checkbox" name="check" id="check" onclick=\'add('.$total.');\' /></td>
<td width="20%">'.$result["invoice_number"].'</td>
<td width="35%">'.$company.'</td>
<td width="20%">'.$result["datetime"].'</td>
<td width="20%">£'.$result["total"].'</td>
</tr>';
}
?>
</table>
</form>
so as you can see it is selecting from the MySQL database and i am trying to make it so when one of the checkboxes is ticked it adds the total into the "thetotal" text field (in form 2) but it is just leaving that box as zero - any ideas on what i could do?
You did not specify the total field for form 1, then it raised javascript error, it wont work.
Check it out
<script>
function add(total)
{
form2.thetotal.value = total + parseFloat(document.form1.formtotal.value);
}
</script>
<form name="form1">
<!-- replace field name formtotal with anything that you want-->
<!-- replace field value with anything that you get from your mysql result-->
<input type="text" name="formtotal" id="formtotal" value="10" />
</form>
Here is how you can do it (assuming total is int and not float):
<script>
function add(total, this_chk_bx)
{
//(if its float, use `parseFloat` instead of `parseInt`)
if(this_chk_bx.checked==true){
//add if its checked
var tot_1 = parseInt(form2.thetotal.value);
form2.thetotal.value = tot_1+parseInt(total);
}
else{
//subtract if its unchecked
}
}
</script>
.
in your php, you have to send the checkbox like this:
onclick=\'add('.$total.', this);\'
.

Dynamic table along with value

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
}

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