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;
Related
Retrieve and print data to textboxes from MySQL DB using Ajax (How to use it twice in the same form.PHP)
while MySQL two tables has the same column 'name' used
Where names database table is:
guid id name
1 101 aaaa
2 102 bbbb
and course_names database table is:
id course_id name
1 win7 Windows 7
2 win8 Windows 8
code 1 form.PHP
<td></td>
<tr>
<script type="text/javascript">
function getname(val) {
$.ajax({
url: 'getinsdata.php',
type: 'POST',
data: 'prn='+val,
dataType: 'json',
success:function(data){
var len = data.length;
if(len > 0){
var id = data[0]['id'];
var name = data[0]['name'];
document.getElementById('name').value = name;
}
}
});
}
</script>
<td align="right">PRN</td>
<td><input type="text" id="prn" name="prn" tabindex="1" onblur="getname(this.value);" <?php if(isset($_GET['id'])) print('value="'.$row['prn'].'"'); ?> /><font color="Red">**</font></td>
<td align="right">Employee Name</td>
<td><input class="p7" id="name" type="text" name="name" tabindex="2" <?php if(isset($_GET['id'])) print('value="'.$row['name'].'"'); ?>Disabled /></td>
</tr>
getinsdata.php
include('config.php');
$id = $_POST['prn'];
$sql = "SELECT * FROM names WHERE id='$id'";
$result = mysqli_query($conn,$sql);
$users_arr = array();
while( $row = mysqli_fetch_array($result) ){
$id = $row['id'];
$name = $row['name'];
$users_arr[] = array("id" => $id, "name" => $name);
}
// encoding array to json format
echo json_encode($users_arr);
exit;
second code at the same form.php
<script type="text/javascript">
function getname2(val2) {
$.ajax({
url: 'getinsdata2.php',
type: 'POST',
data: 'course_guid='+val2,
dataType: 'json',
success:function(data){
var len = data.length;
if(len > 0){
var id = data[0]['id'];
var course_id = data[0]['course_id'];
var name2 = data[0]['name'];
document.getElementById('course_id').value = course_id;
document.getElementById('name').value = name2;
}
}
});
}
</script>
<td align="right">Course ID</td>
<td><input type="text" id="course_guid" name="course_guid" tabindex="3" onblur="getname2(this.value);" <?php if(isset($_GET['id'])) print('value="'.$row['course_guid'].'"'); ?> /><font color="Red">**</font></td>
</tr>
<tr>
<td align="right">Course Adress</td>
<td><input class="p7" id="course_id" type="text" name="course_Addr" tabindex="4" <?php if(isset($_GET['id'])) print('value="'.$row['course_Addr'].'"'); ?>Disabled /></td>
</tr>
<tr>
<td align="right">Course name</td>
<td><input class="p7" id='name' type="text" name="course_name" tabindex="5" <?php if(isset($_GET['id'])) print('value="'.$row['course_name'].'"'); ?>Disabled /></td>
</tr>
getinsdata2.php
<?php
include('config.php');
$id2 = $_POST['course_guid'];
$sql2 = "SELECT * FROM courses_names WHERE id='$id2'";
$result2 = mysqli_query($conn,$sql2);
$users_arr2 = array();
while( $row2 = mysqli_fetch_array($result2) ){
$id2 = $row2['id'];
$course_id = $row2['course_id'];
$name2 = $row2['name'];
$users_arr2[] = array("id" => $id2, "course_id" => $course_id, "name" => $name2);
}
// encoding array to json format
echo json_encode($users_arr2);
exit;
?>
In this case php get confused on selecting the right data.
your kind help is needed.
As workaround from my side I did the following
second code at the same form.php
<script type="text/javascript">
function getname2(val2) {
$.ajax({
url: 'getinsdata2.php',
type: 'POST',
data: 'course_guid='+val2,
dataType: 'json',
success:function(data){
var len = data.length;
if(len > 0){
var id = data[0]['id'];
var course_id = data[0]['course_id'];
var name2 = data[0]['2'];
document.getElementById('course_id').value = course_id;
document.getElementById('2').value = name2;
}
}
});
}
</script>
<td align="right">Course ID</td>
<td><input type="text" id="course_guid" name="course_guid" tabindex="3" onblur="getname2(this.value);" <?php if(isset($_GET['id'])) print('value="'.$row['course_guid'].'"'); ?> /><font color="Red">**</font></td>
</tr>
<tr>
<td align="right">Course Adress</td>
<td><input class="p7" id="course_id" type="text" name="course_Addr" tabindex="4" <?php if(isset($_GET['id'])) print('value="'.$row['course_Addr'].'"'); ?>Disabled /></td>
</tr>
<tr>
<td align="right">Course name</td>
<td><input class="p7" id='2' type="text" name="course_name" tabindex="5" <?php if(isset($_GET['id'])) print('value="'.$row['course_name'].'"'); ?>Disabled /></td>
</tr>
getinsdata2.php
<?php
include('config.php');
$id2 = $_POST['course_guid'];
$sql2 = "SELECT * FROM courses_names WHERE id='$id2'";
$result2 = mysqli_query($conn,$sql2);
$users_arr2 = array();
while( $row2 = mysqli_fetch_array($result2) ){
$id2 = $row2['id']; // column 0
$course_id = $row2['course_id']; // column 1
$name2 = $row2['2']; // where 2 is column name sequence in MySQL Table
$users_arr2[] = array("id" => $id2, "course_id" => $course_id, "2" => $name2);
}
// encoding array to json format
echo json_encode($users_arr2);
exit;
?>
Result
in a invoice form i have a table of which 25 rows are
<table border="1" align="center">
<thead>
<tr>
<th>#</th>
<th>Item Name</th>
<th>Item Code</th>
<th>Quantity</th>
<th>Price</th>
<th>Amount</th>-->
<th>Net Amount</th>
</tr>
</thead>
<tbody>
<?php for($i=1 ; $i<=25 ; $i++) { ?>
<tr>
<th> <?php echo "$i"; ?> </th>
<td><input id="itemName" onBlur="loadAllField()" class="orderInput" type="text" align="center" ></td>
<td><input id="itemCode" onBlur="loadAllField()" class="orderInput" type="text" align="center" ></td>
<td><input id="quantity" class="orderInput" onKeyPress="calqtyprice()" type="text" align="center" ></td>
<td><input id="price" class="orderInput" type="text" align="center" readonly></td>
<td><input id="netAmount" class="orderInput" type="text" align="center" readonly ></td>
</tr>
<?php } ?>
</tbody>
<tfoot>
<tr>
<td id="tdTotal" colspan="2" style="font-size:16px"> <b>Totals</b></td>
<td id="totalspace" colspan="3"> </td>
<td><input id="netTotalAll" class="orderInput" type="text" readonly> </td>
</tr>
</tfoot>
</table>
<p id="msg" align="center"> </p>
and the java script functions are
function loadAllField ()
{
var itemName = document.getElementById("itemName");
var itemCode = document.getElementById("itemCode");
var quantity = document.getElementById("quantity");
var price = document.getElementById("price");
var netAmount = document.getElementById("netAmount");
var msg = document.getElementById("msg");
msg.innerHTML = "";
// check is fill
if ( ( (itemName == null ) || (itemName.value == "") ) && ((itemCode == null ) || (itemCode.value == "")) )
{
msg.innerHTML = "";
itemName.value = null;
itemCode.value = null;
quantity.value = null;
price.value = null;
netAmount.value = null;
}
// load id if item name give and load name if item code given
if ((itemName.value == "detol") || (itemCode.value=="1") )
{
var itemName = document.getElementById("itemName");
var itemCode = document.getElementById("itemCode");
var quantity = document.getElementById("quantity");
var price = document.getElementById("price");
var netAmount = document.getElementById("netAmount");
var msg = document.getElementById("msg");
msg.innerHTML = "";
itemName.value = "detol";
itemCode.value = "1";
quantity.value = "";
price.value = "40";
netAmount.value = "";
}
else if ( (itemName.value == "robin") || (itemCode.value == "2") )
{
msg.innerHTML = "";
itemName.value = "robin";
itemCode.value = "2";
quantity.value = "";
price.value = "90";
netAmount.value = "";
}
else
{
msg.innerHTML = "Product not find";
//msg.innerHTML.blink();
itemName.value = "";
itemCode.value = "";
quantity.value = "";
price.value = "";
netAmount.value = "";
}
} // end of load id function
function calqtyprice()
{
for ( i=1; i==25; i++)
{
var price = document.getElementById("price");
var quantity = document.getElementById("quantity");
var netAmount = document.getElementById("netAmount");
var netTotalAll = document.getElementById("netTotalAll");
var netamt = price.value * quantity.value ;
netAmount.value = netamt;
netTotalAll = netAmount.value + netAmount.value;
}
}
the problem is how to go through every row and getting values from input and calculate and show nettotal in the last row.
Or is there any mechanism for this or tutorial.
Lets assume you created elements with unique ids as follows
<input type="text" id="price_1"
in your case you can use the $i value to create uniqly named ids.
<input type="text" id="price_<?php echo $i; ?>"
then in your javascript loop
for ( i=1; i<=25; i++) {
var price = document.getElementById("price_" + i);
gives you access to each unique element.
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; ?>">
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.
With the help of members from this post, I converted from prototype to jQuery.
function jsUpdateCart(){
var parameter_string = '';
allNodes = document.getElementsByClassName("process");
for(i = 0; i < allNodes.length; i++) {
var tempid = allNodes[i].id;
var temp = new Array;
temp = tempid.split("_");
var real_id = temp[2];
var real_value = allNodes[i].value;
parameter_string += real_id +':'+real_value+',';
}
var params = 'ids='+parameter_string;
$.ajax({
type: "POST",
url: "http://127.0.0.1/codeigniter_shopping/index.php/welcome/ajax_cart",
data: params,
success: function( r ) {
$('#ajax_msg').html( r );
location.reload( true );
}
});
}
function jsRemoveProduct(id){
var params = 'id='+id;
$.ajax({
type: "POST",
url: "http://127.0.0.1/codeigniter_shopping/index.php/welcome/ajax_cart_remove",
data: params,
success: function( r ) {
$('#ajax_msg').html( r );
location.reload( true );
}
});
}
ajax_cart_remove works in both Firefox and IE, but update works with Firefox, but it doesn't with IE 7/8.
Could anyone give me some suggestions please.
You can see the original prototype code here.
ajax_cart and ajax_cart_remove in controllers are followings.
function ajax_cart(){
$this->MOrders->updateCartAjax($this->input->post('ids'));
}
function ajax_cart_remove(){
$this->MOrders->removeLineItem($this->input->post('id'));
}
And models for MOders are following.
function removeLineItem($id){
$id = id_clean($id);
$totalprice = 0;
$cart = $_SESSION['cart'];
if (isset($cart[$id])){
unset($cart[$id]);
foreach ($cart as $id => $product){
$totalprice += $product['price'] * $product['count'];
}
$_SESSION['totalprice'] = $this->format_currency($totalprice);
$_SESSION['cart'] = $cart;
echo "Product removed.";
}else{
echo "Product not in cart!";
}
}
function updateCartAjax($idlist){
$cart = $_SESSION['cart'];
$records = explode(',',$idlist);
$updated = 0;
$totalprice = $_SESSION['totalprice'];
if (count($records)){
foreach ($records as $record){
if (strlen($record)){
$fields = explode(":",$record);
$id = id_clean($fields[0]);
$ct = $fields[1];
if ($ct > 0 && $ct != $cart[$id]['count']){
$cart[$id]['count'] = $ct;
$updated++;
}elseif ($ct == 0){
unset($cart[$id]);
$updated++;
}
}
}
if ($updated){
$totalprice=0;
foreach ($cart as $id => $product){
$totalprice += $product['price'] * $product['count'];
}
$_SESSION['totalprice'] = $this->format_currency($totalprice);
$_SESSION['cart'] = $cart;
switch ($updated){
case 0:
$string = "No records";
break;
case 1:
$string = "$updated record";
break;
default:
$string = "$updated records";
break;
}
echo "$string updated";
}else{
echo "No changes detected";
}
}else{
echo "Nothing to update";
}
}
The following is the html output of form
<form action="http://127.0.0.1/codeigniter_shopping_copy2/index.php/welcome/checkout" method="post"><table border='1' cellspacing='0' cellpadding='5'>
<tr valign='top'>
<td><input type="text" name="li_id[10]" value="1" id="li_id_10" class="process" size="5" /></td>
<td id='li_name_10'>Dress 1</td>
<td id='li_price_10'>33.95</td>
<td id='li_total_10'>33.95</td>
<td><input type='button' name='delete' value='delete' onclick='jsRemoveProduct(10)'></td>
</tr>
<tr valign='top'>
<td><input type="text" name="li_id[6]" value="2" id="li_id_6" class="process" size="5" /></td>
<td id='li_name_6'>Shoes 1</td>
<td id='li_price_6'>23.95</td>
<td id='li_total_6'>47.90</td>
<td><input type='button' name='delete' value='delete' onclick='jsRemoveProduct(6)'></td>
</tr>
<tr valign='top'>
<td colspan='3'> </td>
<td colspan='2'>81.85
<input type="hidden" name="name" value="total" />
<input type="hidden" name="id" value="total" />
<input type="hidden" name="value" value="81.85" />
</td>
</tr>
<tr valign='top'>
<td colspan='3'> </td>
<td colspan='2'><input type='button' name='update' value='update' onclick='jsUpdateCart()'/></td>
</tr>
<tr valign='top'>
<td colspan='3'> </td>
<td colspan='2'><input type="submit" name="submit" value="checkout" /></td>
</tr>
</table>
</form>
I don't think IE supports document.getElementByClassName("")
Try replacing
allNodes = document.getElementsByClassName("process");
with
allNodes = $(".process");
wich is the JQuery way.
In IE8 just bring up the Web Developer Toolkit and put a break point at this line:
$('#ajax_msg').html( r );
I would also put a break point at the .ajax call here:
var params = 'ids='+parameter_string;
$.ajax({
then see what happens.
This way you can ensure you are getting to it properly, else IE may have a problem before you get here, or, if you get here then you need to see if it goes out to the service and back, which is what the first url will tell you. Then single-step through the success code and see if it jumps out at some point due to an error.
Once you know for a fact that this code is the problem then you can update with what you have learned, but I have used this function in IE7 and 8 so it should work fine.