Passing DOM table variables to PHP - php

I am not very experienced just a learner.
Now come to the question.
I have a dynamic table codes are below: works fine as intended.
<head>
<style type="text/css">
<!--
#tblitemsgrid
td {
padding: 0.5em;
}
.classy0 { background-color: #234567; color: #89abcd; }
.classy1 { background-color: #89abcd; color: #234567; }
th {
padding: 0.5em;
background:#39C;
text-align:center;
}
-->
</style>
<script type="text/javascript">
var INPUT_NAME_PREFIX = 'input'; // this is being set via script
var RADIO_NAME = 'totallyrad'; // this is being set via script
var TABLE_NAME = 'tblitemsgrid'; // this should be named in the HTML
var ROW_BASE = 1; // first number (for display)
var hasLoaded = false;
window.onload=fillInRows;
function fillInRows()
{
hasLoaded = true;
addRowToTable();
}
// CONFIG:
// myRowObject is an object for storing information about the table rows
function myRowObject(one, two, three, four, five)
{
this.one = one; // text object
this.two = two; // text object
this.three = three; // text object
this.four = four; // text object
}
/*
* insertRowToTable
* Insert and reorder
*/
function insertRowToTable()
{
if (hasLoaded) {
var tbl = document.getElementById(TABLE_NAME);
var rowToInsertAt = tbl.tBodies[0].rows.length;
for (var i=0; i<tbl.tBodies[0].rows.length; i++) {
}
addRowToTable(rowToInsertAt);
reorderRows(tbl, rowToInsertAt);
}
}
/*
* addRowToTable
function addRowToTable(num)
{
if (hasLoaded) {
var tbl = document.getElementById(TABLE_NAME);
var nextRow = tbl.tBodies[0].rows.length;
var iteration = nextRow + ROW_BASE;
if (num == null) {
num = nextRow;
} else {
iteration = num + ROW_BASE;
}
// add the row
var row = tbl.tBodies[0].insertRow(num);
// CONFIG: requires classes named classy0 and classy1
row.className = 'classy' + (iteration % 2);
// CONFIG: This whole section can be configured
// cell 0 - text - Serial Number
var cell0 = row.insertCell(0);
var textNode = document.createTextNode(iteration);
cell0.appendChild(textNode);
// cell 1 - input text - Account name
var cell1 = row.insertCell(1);
var txtInpACC = document.createElement('input');
txtInpACC.setAttribute('type', 'text');
txtInpACC.setAttribute('name', 'accname' + iteration);
txtInpACC.setAttribute('size', '40');
txtInpACC.setAttribute('value', iteration);
cell1.appendChild(txtInpACC);
// cell 2 - input box- Dr amount
var cell2 = row.insertCell(2);
var txtInpDR = document.createElement('input');
txtInpDR.setAttribute('type', 'text');
txtInpDR.setAttribute('name', 'DrAmount' + iteration);
txtInpDR.setAttribute('size', '10');
txtInpDR.setAttribute('value', iteration); // iteration included for debug purposes
cell2.appendChild(txtInpDR);
// cell 3 - input box- Cr amount
var cell3 = row.insertCell(3);
var txtInpCR = document.createElement('input');
txtInpCR.setAttribute('type', 'text');
txtInpCR.setAttribute('name', 'CrAmount' + iteration);
txtInpCR.setAttribute('size', '10');
txtInpCR.setAttribute('value', iteration); // iteration included for debug purposes
cell3.appendChild(txtInpCR);
// cell 4 - input button - Delete
var cell4 = row.insertCell(4);
var btnEl = document.createElement('input');
btnEl.setAttribute('type', 'button');
btnEl.setAttribute('value', 'Delete');
btnEl.onclick = function () {deleteCurrentRow(this)};
cell4.appendChild(btnEl);
// Pass in the elements you want to reference later
// Store the myRow object in each row
row.myRow = new myRowObject(textNode, txtInpACC, txtInpDR, txtInpCR, btnEl);
}
}
// CONFIG: this entire function is affected by myRowObject settings
function deleteCurrentRow(obj)
{
if (hasLoaded) {
var oRows = document.getElementById('tblitemsgrid').getElementsByTagName('tr');
var iRowCount = (oRows.length - 2);
if (iRowCount <1+1) {
alert('Your table has ' + iRowCount + ' row(s). Row count can not be zero.');
return
}
var delRow = obj.parentNode.parentNode;
var tbl = delRow.parentNode.parentNode;
var rIndex = delRow.sectionRowIndex;
var rowArray = new Array(delRow);
deleteRows(rowArray);
reorderRows(tbl, rIndex);}
}
function reorderRows(tbl, startingIndex)
{
if (hasLoaded) {
if (tbl.tBodies[0].rows[startingIndex]) {
var count = startingIndex + ROW_BASE;
for (var i=startingIndex; i<tbl.tBodies[0].rows.length; i++) {
// CONFIG: next line is affected by myRowObject settings
tbl.tBodies[0].rows[i].myRow.one.data = count; // text
// CONFIG: next line is affected by myRowObject settings
tbl.tBodies[0].rows[i].myRow.two.name = INPUT_NAME_PREFIX + count; // input text
var tempVal = tbl.tBodies[0].rows[i].myRow.two.value.split(' ');
tbl.tBodies[0].rows[i].myRow.two.value = count + ' was' + tempVal[0];
// CONFIG: next line is affected by myRowObject settings
tbl.tBodies[0].rows[i].myRow.four.value = count; // input radio
// CONFIG: requires class named classy0 and classy1
tbl.tBodies[0].rows[i].className = 'classy' + (count % 2);
count++;
}
}
}
}
function deleteRows(rowObjArray)
{
if (hasLoaded) {
for (var i=0; i<rowObjArray.length; i++) {
var rIndex = rowObjArray[i].sectionRowIndex;
rowObjArray[i].parentNode.deleteRow(rIndex);
}
}
}
function openInNewWindow(frm)
{
// open a blank window
var aWindow = window.open('', 'TableAddRow2NewWindow',
'scrollbars=yes,menubar=yes,resizable=yes,toolbar=no,width=400,height=400');
// set the target to the blank window
frm.target = 'TableAddRow2NewWindow';
// submit
frm.submit();
}
</script>
</head>
<body>
<form action="tableaddrow_nw.php" method="get">
<p>
<input type="button" value="Add" onclick="addRowToTable();" />
<input type="button" value="Insert [I]" onclick="insertRowToTable();" />
<!--<input type="button" value="Delete [D]" onclick="deleteChecked();" />-->
<input type="button" value="Submit" onclick="openInNewWindow(this.form);" />
</p>
<table border="0" cellspacing="0" id="tblitemsgrid" width=600>
<thead>
<tr>
<th colspan="5">Sample table</th>
</tr>
<tr>
<th>E.#</th>
<th>Account name</th>
<th>Debit</th>
<th>Credit</th>
<th></th>
</tr>
</thead>
<tbody></tbody>
</table>
</form>
</body>
</html>
This is a processing page:
<head>
<title>Table Add Row - new window</title>
<script language="JavaScript">
<!--
function printToPage()
{
var pos;
var searchStr = window.location.search;
var searchArray = searchStr.substring(1,searchStr.length).split('&');
var htmlOutput = '';
for (var i=0; i<searchArray.length; i++) {
htmlOutput += searchArray[i] + '<br />';
}
return(htmlOutput);
}
//-->
</script>
</head>
<body>
<b>MREDKJ's Table Add Row</b>
<br />
Below should be the name/value pairs that were submitted:
<p>
<script language="JavaScript">
<!--
document.write(printToPage());
//-->
</script>
</p>
</body>
</html>
the above displays a result:
accname1=1
DrAmount1=1
CrAmount1=1
input2=2+was2
DrAmount2=2
CrAmount2=2
input3=3+was3
DrAmount3=3
CrAmount3=3
input4=4+was4
DrAmount4=4
CrAmount4=4
how can I pass javascript variables into PHP (which is server side and client side) in the above case ?
thanks alot in advance.

The way to pass variables from client-side to server-side is via HTTP Request. So either you redirect to a PHP page passing in the variable as GET query strings or POST data or you can also do an AJAX call of either GET or POST.

You can use jQuery and ajax to pass these informations to server easy way
And remember. PHP isn't client side language
$.ajax({
'url': 'ajax.php',
'type': 'POST',
'data': 'accname1='+accname1+'&input1='+input1+'&input2='+input2+'&input3='+input3+'&DrAmount1='+DrAmount1+'&DrAmount2='+DrAmount2+'&DrAmount3='+DrAmount3+'&CrAmount1='+CrAmount1'&CrAmount2='+CrAmount2'&CrAmount3='+CrAmount3,
'success': function(){
alert('data sent');
}
});

Related

I can not take all the arrays for serialize jquery

I have a page that has three checkbox lists, the three are dynamically generated
what I want and that as the User is clicking the checkbox values ​​are passed via post, but I only managed to catch Esto values ​​of the first list
I did the code like this:
$("body").find(".fcID").click(function(){
// var v = $(this).val();
//alert(v);
var form = jQuery('#form');
valor = form.serialize();
$.ajax({
type : "POST",
url:"biblioteca/filtra.php",
data: valor,
success: function(data){
$("#tabelafiltro").html(data);
}
});
in html, I put a form with the id of her form and name the form
within that form, I have the checkboxes, so:
<form name="form" id="form" action="" method="post">
<table>
<tr>
<td><input type="checkbox" class="fcID" value="<?php echo $linha['fm-cod-com'] ?>" name="fcID[]"/></td>
</tr>
</table>
<table>
<tr>
<td><input type="checkbox" class="fcID" name="fam[]" value="<?php echo $linha['fm-codigo'] ?>" /></td>
</tr>
</table>
</form>
and the php:
$id = $_POST['fcID'];
$fam = $_POST['fam'];
echo(count($fam)) . " + " . count($id);
somebody help me?
Your code is correct, are u sure that the fam[] checkboxes are checked? Checkboxes will serialize only if they have atribute checked="checked".
Unfortunately the "name" is not converted to an array by jQuery.. so instead of this:
echo $_POST['fcID'][0]; // undefined
you have this
echo $_POST['fcID[]']; // expected value
I created the following. It has some limitations, but should do what you want. I appreciate if you can rate my answer.
var form = jQuery('#form');
valor = form.formToObj();
// formToObj (c) 2012 Frank Forte.
// Please contact me for a free license to use on personal or business website
// #frankforte or frank # interactinet .com!
jQuery.fn.formToObj = function()
{
var obj = {}
jQuery("input,select,textarea",this).each(function(){
if(jQuery(this).attr("disabled")){
return;
}
var n = jQuery(this).attr("name") || jQuery(this).attr("id")
var v = jQuery(this).val();
// e.g.<input name="test[one][two][three]" value="hello world">
if(!n.match(/\[/))
{
obj[n] = v
}
else
{
// get keys of array, e.g. "one","two","three"
var keys = []
nkeys= n.split('[')
var i = 0;
for(k in nkeys)
{
if(i > 0)
{
var nk = nkeys[k]
if(typeof nk == "string")
{
if(nk.match(/\]/))
{
nk = nk.replace("]","")
}
keys.push(nk);
}
}
i++
}
// name e.g. "test"
n = n.replace(/^([^\[\]]+)\[.*$/i,"$1");
// create object and add value then array keys from bottom up
var iobj = {}
for(i = keys.length; i > 0; i--)
{
j = i-1;
var k = keys[j]
if(k==""){k = 0;}
if(i == keys.length)
{
iobj[k] = v
}
else
{
iobj[k] = iobj
}
}
// Need to start with obj[n] and add new values under appropriate keys
// prevents unsetting or overwriting keys deeper than n
if(typeof obj[n] == "undefined")
{
obj[n] = {}
}
obj[n][k] = iobj[k]
}
})
return obj
}

How to get total value on dynamic value?

I have form like this :
<input type='hidden' name='seq' id='idseq' value='1' />
<div id='add_field' class='locbutton'><a href='#' title='Add'>Add</a></div>
<div id='remove_field' class='locbutton2'><a href='#' title='Delete'>Delete</a></div>
<div id="idcover">
1.<br />
<div class="group">
<div class="satu"><input type='text' name='score[1][]' id='score[1][]'></div>
<div class="dua"><input type='text' name='weight[1][]' id='weight[1][]'> %</div>
<div class="tiga"><input type='text' name='weightscore[1][]' id='weightscore[1][]'
disabled></div>
</div>
</div>
<br /><br />
<div id='idtotalcover' class='totalcover'>
Total <div class='total'><input type='text' name='total' id='idtotal' disabled /></div>
</div>
This is the jquery script:
<script type="text/javascript">
$(document).ready(
function ()
{
$("input[id^=score],input[id^=weight]").bind("keyup", recalc);
recalc();
var counter = $("#idseq").val();
$("#add_field").click(function ()
{
counter++;
$.ajax({
url: 'addinput.php',
dataType: "html",
data: "count="+counter,
success: function(data)
{
$('#idcover').append(data);
$('.dua input').keyup(function()
{
var $duaInput = $(this);
var weight=$duaInput.val();
var score=$duaInput.closest(".group").find('.satu input').val();
$.ajax({
url: "cekweightscore.php",
data: "score="+score+"&weight="+weight,
success:
function(data)
{
$duaInput.closest(".group").find('.tiga input').val(data);
}//success
});//ajax
});
}//success
});//ajax
});
});
function recalc()
{
var a=$("input[id^=score]");
var b=$("input[id^=weight]");
$("[id^=weightscore]").calc("(score * weight)/100",{score: a,weight: b},
function (s)
{
return s.toFixed(2);
},
function ($this){
//function($("[id^=weightscore]")){
// sum the total of the $("[id^=total_item]") selector
//alert($this);
//var sum = $this.sum();
var sum=$this.sum();
$("#idtotal").val(sum.toFixed(2));
}
);
}
</script>
This is the php code:
<?
$count=$_GET['count'];
echo"
<br>
$count
<div class='group' >
<div class='satu'>
<input type='text' name='score[$count][]' id='score[$count][]'>
</div>
<div class='dua'>
<input type='text' name='weight[$count][]' id='weight[$count][]'> %
</div>
<div class='tiga'>
<input type='text' name='weightscore[$count][]' id='weightscore[$count][]' disabled>
</div>
</div>";
?>
When I click the Add button, i cant get value on new form so that the new form cannot be calculated. What can i do to get total value on dynamic value ?
I remember reading this exact same question yesterday and I still have no idea of what you're trying to do.
Why are you adding inputs through AJAX instead of creating them in Javascript from the beginning? AJAX calls are expensive and are recommended to be used when you need to update/retrieve values from the server.
Why are you trying to do your calculations on the server side anyway? If you're dealing with dynamic input, you should be doing the calculations client side, then update the server when you're done.
Why do you use obscure name/id attribute values?
Anyway,
I created this example, it contains two different solutions, one with a ul and a table. Hopefully, the example matches what you're trying to do and might give you some insight.
I use a timer to update simulated server data. The timer is set to the variable update_wait. The other dynamic calculations are done client side.
I'll post the Javascript code as well, in case you don't like to fiddle
Example | Javascript
var update_server_timer = null,
update_wait = 1000; //ms
var decimals = 3;
/**********************
List solution
**********************/
function CreateListRow(){
var eLi = document.createElement("li"),
eScore = document.createElement("div"),
eWeight = document.createElement("div"),
eWeightScore = document.createElement("div");
var next_id = $("#cover li:not(.total)").length + 1
eScore.className = "score";
eWeight.className = "weight";
eWeightScore.className = "weightscore";
//Score element
var eScoreInput = document.createElement("input");
eScoreInput.type = "text";
eScoreInput.name = "score_"+next_id;
eScoreInput.id = "score_"+next_id;
eScore.appendChild(eScoreInput);
//Weight element
var eWeightInput = document.createElement("input");
eWeightInput.type = "text";
eWeightInput.name = "weight_"+next_id;
eWeightInput.id = "weight_"+next_id;
var eWeightPerc = document.createElement("div");
eWeightPerc.className = "extra";
eWeightPerc.innerHTML = "%";
eWeight.appendChild(eWeightInput);
eWeight.appendChild(eWeightPerc);
//Weightscore element
var eWeightScoreInput = document.createElement("input");
eWeightScoreInput.type = "text";
eWeightScoreInput.name = "weight_"+next_id;
eWeightScoreInput.id = "weight_"+next_id;
eWeightScore.appendChild(eWeightScoreInput);
$(eScore).keyup(function(){
CalculateListRow($(this).closest("li"));
});
$(eWeight).keyup(function(){
CalculateListRow($(this).closest("li"));
});
//item element
eLi.appendChild(eScore);
eLi.appendChild(eWeight);
eLi.appendChild(eWeightScore);
return eLi;
}
function CalculateListRowTotal(){
var fTotal = 0;
$("#cover li:not(.total) div:nth-child(3) input").each(function(){
var fVal = parseFloat($(this).val());
if(isNaN(fVal)) fVal = 0;
fTotal += fVal;
});
fTotal = parseFloat(fTotal.toFixed(decimals));
$("#cover li.total div input").val(fTotal);
//Update server variables here
RestartUpdateServerTimer();
}
function CalculateListRow($Li){
var fScore = parseFloat($("div.score input", $Li).val()),
fWeight = parseFloat($("div.weight input", $Li).val())/100,
fRes = (fScore*fWeight);
if(isNaN(fRes)) fRes = 0.00;
$("div.weightscore input", $Li).val(parseFloat(fRes.toFixed(decimals)));
CalculateListRowTotal();
}
$("#cover li div.weight input, #cover li div.score input").keyup(function(){
CalculateListRow($(this).closest("li"));
});
function AddListRow(){
$("#cover li.total").before(CreateListRow());
RestartUpdateServerTimer();
}
function RemoveListRow(){
$("#cover li.total").prev().remove();
CalculateListRowTotal();
}
$(".left_container .menu .add").click(function(){ AddListRow(); });
$(".left_container .menu .rem").click(function(){ RemoveListRow(); });
/**********************
Table solution
**********************/
function CreateTableRow(){
var eTr = document.createElement("tr"),
eTds = [document.createElement("td"),
document.createElement("td"),
document.createElement("td")];
var next_id = $("#cover2 tbody tr").length + 1;
$(eTds[0]).append(function(){
var eInput = document.createElement("input");
eInput.type = "text";
eInput.name = eInput.id = "score_"+next_id;
$(eInput).keyup(function(){
CalculateTableRow($(this).closest("tr"));
});
return eInput;
});
$(eTds[1]).append(function(){
var eRelativeFix = document.createElement("div"),
eInput = document.createElement("input"),
eExtra = document.createElement("div");
eRelativeFix.className = "relative_fix";
eInput.type = "text";
eInput.name = eInput.id = "weight_"+next_id;
eExtra.innerHTML = "%";
eExtra.className = "extra";
eRelativeFix.appendChild(eInput);
eRelativeFix.appendChild(eExtra);
$(eInput).keyup(function(){
CalculateTableRow($(this).closest("tr"));
});
return eRelativeFix;
});
$(eTds[2]).append(function(){
var eInput = document.createElement("input");
eInput.type = "text";
eInput.name = eInput.id = "weightscore_"+next_id;
return eInput;
});
for(i = 0; i < eTds.length; i++){
eTr.appendChild(eTds[i]);
}
return eTr;
}
function CalculateTableRowTotals(){
var $rows = $("#cover2 tbody tr"),
$totals = $("#cover2 tfoot tr th");
var fTotal = [];
//Each row
$rows.each(function(){
var $columns = $("td", this);
//Each column
$columns.each(function(i, e){
var fVal = parseFloat($("input", e).val());
if(isNaN(fVal)) fVal = 0;
if(isNaN(fTotal[i])) fTotal[i] = 0;
fTotal[i] += fVal;
});
});
for(i = 0; i < fTotal.length; i++){
fTotal[i] = parseFloat(fTotal[i].toFixed(decimals));
}
fTotal[1] = (fTotal[2]/fTotal[0]*100).toFixed(decimals)+"%";
fTotal[2] = parseFloat(fTotal[2].toFixed(decimals));
$totals.each(function(i, e){
$(this).text(fTotal[i]);
});
//Update server variables here
RestartUpdateServerTimer();
}
function CalculateTableRow($Tr){
var fScore = parseFloat($("td:nth-child(1) input", $Tr).val()),
fWeight = parseFloat($("td:nth-child(2) input", $Tr).val())/100,
fRes = (fScore*fWeight);
if(isNaN(fRes)) fRes = 0.00;
$("td:nth-child(3) input", $Tr).val(parseFloat(fRes.toFixed(decimals)));
CalculateTableRowTotals();
}
function AddTableRow(){
if($("#cover2 tbody tr").length == 0){
$("#cover2 tbody").append(CreateTableRow());
}else{
$("#cover2 tbody tr:last-child").after(CreateTableRow());
}
RestartUpdateServerTimer();
}
function RemoveTableRow(){
$("#cover2 tbody tr:last-child").remove();
CalculateTableRowTotals();
}
$(".right_container .menu .add").click(function(){ AddTableRow(); });
$(".right_container .menu .rem").click(function(){ RemoveTableRow(); });
$("#cover2 tbody tr td:nth-child(1) input, #cover2 tbody tr td:nth-child(2) input").keyup(function(){
CalculateTableRow($(this).closest("tr"));
});
/**********************
Server data
- Simulates the data on the server,
- whether it be in a SQL server or session data
**********************/
var ServerData = {
List: {
Count: 3,
Total: 5.50
},
Table: {
Count: 3,
Totals: [65, 8.46, 5.50]
}
};
function UpdateServerData(){
//List
var ListCount = $("#cover li:not(.total)").length,
ListTotal = $("#cover li.total input").val();
//Table
var TableCount = $("#cover2 tbody tr").length,
TableTotals = [];
$("#cover2 tfoot th").each(function(i, e){
TableTotals[i] = parseFloat($(this).text());
});
var data = {
json: JSON.stringify({
List: {
Count: ListCount,
Total: ListTotal
},
Table: {
Count: TableCount,
Totals: TableTotals
}
})
}
//Update
$.ajax({
url: "/echo/json/",
data: data,
dataType: "json",
type:"POST",
success: function(response){
ServerData.List = response.List;
ServerData.Table = response.Table;
var displist = "Server data<h1>List</h1><ul><li>Count: "+ServerData.List.Count+"</li><li>Total: "+ServerData.List.Total+"</li></ul>",
disptable = "<h1>Table</h1><ul><li>Count: "+ServerData.Table.Count+"</li>";
for(i=0; i<ServerData.Table.Totals.length; i++)
disptable += "<li>Total "+i+": "+ServerData.Table.Totals[i]+"</li>";
disptable += "</ul>";
$("#server_data").html(displist+"<br />"+disptable).effect("highlight");
}
});
}
function RestartUpdateServerTimer(){
if(update_server_timer != null) clearTimeout(update_server_timer);
update_server_timer = setTimeout(function(){
UpdateServerData()
}, update_wait);
}
UpdateServerData();
Update
Since you have a hard time grasping the concept, here's a copy paste solution that will work for you without having to use AJAX. I would like to point out that your HTML markup and general coding is a total mess...
Example | Code
<script type="text/javascript">
$(document).ready(function(){
function CreateInput(){
var $group = $("<div>"),
$score = $("<div>"),
$weight = $("<div>"),
$weightscore = $("<div>");
var group_count = $("div.group").length+1;
$group.addClass("group");
$score.addClass("satu");
$weight.addClass("dua");
$weightscore.addClass("tiga");
var $input_score = $("<input>"),
$input_weight = $("<input>"),
$input_weightscore = $("<input>")
$input_score
.attr("name", "score["+group_count+"][]")
.attr("type", "text")
.attr("id", "score["+group_count+"][]");
$input_weight
.attr("name", "weight["+group_count+"][]")
.attr("type", "text")
.attr("id", "weight["+group_count+"][]");
$input_weightscore
.attr("name", "weightscore["+group_count+"][]")
.attr("type", "text")
.attr("id", "weightscore["+group_count+"][]")
.attr("disabled", true);
$input_score.keyup(function(){
CalculateGroup($(this).parents(".group"));
});
$input_weight.keyup(function(){
CalculateGroup($(this).parents(".group"));
});
$score.append($input_score);
$weight.append($input_weight);
$weightscore.append($input_weightscore);
$group.append($score)
.append($weight)
.append($weightscore);
return $group;
}
function CalculateGroup($group){
var fScore = parseFloat($(".satu input", $group).val()),
fWeight = parseFloat($(".dua input", $group).val()),
fWeightScore = parseFloat((fScore*(fWeight/100)).toFixed(2));
if(isNaN(fWeightScore)) fWeightScore = 0;
$(".tiga input", $group).val(fWeightScore);
CalculateTotal();
}
function CalculateTotal(){
var fWeightScoreTotal = 0;
$("#idcover div.group div.tiga input").each(function(){
var fTotal = parseFloat(parseFloat($(this).val()).toFixed(2));
if(isNaN(fTotal)) fTotal = 0;
fWeightScoreTotal += fTotal;
});
fWeightScoreTotal = parseFloat(fWeightScoreTotal.toFixed(2));
$("#idtotalcover div.total input").val(fWeightScoreTotal);
}
$(".satu input, .dua input").keyup(function(){
CalculateGroup($(this).parents(".group"));
});
$("#add_field a").click(function(e){
$("#idcover").append(CreateInput());
e.preventDefault();
});
$("#remove_field a").click(function(e){
$("#idcover div.group:last-child").remove();
CalculateTotal();
e.preventDefault();
});
});
</script>

undefined value single checkbox javascript to another page

i have two page, the first page is index.php i also using facebox framework in it. the second page is addevent.php i've tried in many ways to catch the value of single checkbox in addevent.php and passing it to index.php. but it didn't show the value. so is there someting wrong with my code ? what i'm miss ? any help would be appreciate..
index.php
echo ">".$check=$_REQUEST['check'];
echo "check[0]: ".$check[0];
&lthead&gt
&ltscript src="inc/jquery-1.4.4.min.js" type="text/javascript"&gt&lt/script&gt
&ltscript src="inc/facebox.js" type="text/javascript"&gt&lt/script&gt
&ltbody>
&lta href="addevent.php" rel="facebox" &gtlink&lt/a&gt
&lt/body>
addevent.php
&lthead&gt
&ltscript src="inc/jquery-1.4.4.min.js" type="text/javascript"&gt&lt/script&gt
&ltscript src="inc/facebox.js" type="text/javascript"&gt&lt/script&gt
&ltscript language="javascript" type="text/javascript"&gt
function AddEventAgenda(){
//--- i've tried this method & firebug said:document.eventAgendaForm.checkName[0] is undefined----
var elemLength = document.eventAgendaForm.checkName.length;
if (elemLength==undefined) {
elemLength=1;
if (document.eventAgendaForm.checkName.checked) {
// we know the one and only is checked
var check = "&check[0]=" + document.eventAgendaForm.checkName[0].value;
}
} else {
for (var i = 0; i&ltelemLength; i++) {
if (eventAgendaForm.checkName[i].checked) {
var check = "&check["+i+"]=" + document.eventAgendaForm.checkName[i].value + check;
}
}
}
//--- also this one same firebug said:document.eventAgendaForm.checkName[0] is undefined---
var len = document.eventAgendaForm.checkName.length;
if(len == undefined) len = 1;
for (i = 0; i &lt len; i++){
var check = "&check["+i+"]=" + document.eventAgendaForm.checkName[i].value + check;
}
//--- and this one same firebug said:document.eventAgendaForm.checkName[0] is undefined---
var formNodes = document.eventAgendaForm.getElementsByTagName('input');
for (var i=0;i&ltformNodes.length;i++) {
/* do something with the name/value/id or checked-state of formNodes[i] */
if(document.eventAgendaForm.checkName[i].checked){
var check = "&check["+i+"]=" + document.eventAgendaForm.checkName[i].value + check;
}
}
//--- and this one same firebug said:document.eventAgendaForm.checkName[0] is undefined---
if (typeof document.eventAgendaForm.checkName.length === 'undefined') {
/*then there is just one checkbox with the name 'user' no array*/
if (document.eventAgendaForm.checkName.checked == true )
{
var check = "&check[0]=" + document.eventAgendaForm.checkName[0].value;
}
}else{
/*then there is several checkboxs with the name 'user' making an array*/
for(var i = 0, max = document.eventAgendaForm.checkName.length; i &lt max; i++){
if (document.eventAgendaForm.checkName[i].checked == true )
{
var check = "&check["+i+"]=" + document.eventAgendaForm.checkName[i].value + check;
}
}
}
//-----------------------------------------------
window.location="index.php?tes=1" + check; // display the result
$(document).trigger('close.facebox');
}
&lt/script&gt
&ltscript type="text/javascript"&gt
// i don't know if these code have connection with checkbox or not?
function addLoadEvent(func) {
var oldonload = window.onload;
if (typeof window.onload != "function") {
window.onload = func;
} else {
window.onload = function () {
oldonload();
func();
}
}
}
addLoadEvent(function () {
initChecklist();
});
function initChecklist() {
if (document.all && document.getElementById) {
// Get all unordered lists
var lists = document.getElementsByTagName("ul");
for (i = 0; i &lt lists.length; i++) {
var theList = lists[i];
// Only work with those having the class "checklist"
if (theList.className.indexOf("checklist") &gt -1) {
var labels = theList.getElementsByTagName("label");
// Assign event handlers to labels within
for (var j = 0; j &lt labels.length; j++) {
var theLabel = labels[j];
theLabel.onmouseover = function() { this.className += " hover"; };
theLabel.onmouseout = function() { this.className = this.className.replace(" hover", ""); };
}
}
}
}
}
&lt/script&gt
&lt/head&gt
&ltform name="eventAgendaForm" id="eventAgendaForm" &gt
&ltul class="checklist cl3"&gt
&ltli &gt&ltlabel for="c1"&gt
&ltinput id="checkId" name="checkName" value="1" type="checkbox" &gt
&lt/label&gt&lt/li&gt&lt/ul&gt
&ltinput class="tombol" type="button" name="Add" value="Add" onclick="AddEventAgenda()" /&gt
&lt/form&gt
why not use jQuery if you are including jQuery library?
var checkbox_val=jQuery("#CHECKBOX_ID_HERE").val();//gets you the value regardless if checked or not
var checkbox_val=jQuery("#CHECKBOX_ID_HERE").attr("checked"); //returns checked status
or
var global_variable=""; //should be initialized outside any function
jQuery("#FORM_ID_HERE").children(":input[type='checkbox']").each(function(){
if (jQuery(this).attr("checked"))global_variable+="&"+jQuery(this).attr("name")+"="+jQuery(this).val();
});
this is just a suggestion to start from, not ideal. the ideal part is to use [] in your form.

How auto updated the database without refresh with ajax?

i'm new here. i just create a code which can read the data from mysql database.
But when i add in new data inside databse, my php page cant updated own automatic.
I want the page can updated automaticly withour press f5 button and refresh.
Can anyone help me solve this?
Get any misstake??
<script type="text/javascript">
function List(){
var ajaxRequest;
var selectedProduct = "";
var product = document.getElementById('product');
var output ="";
var k = 0;
// var name = new Array;
// var model = new Array;
var unitprice = new Array;
var queryString = new Array;
queryString = "&name=" + txtname + "&model=" + txtmodel + ;
ajaxRequest.open("GET", $productPrice + queryString, true);
ajaxRequest.send(null);
ajaxRequest.open("GET", $productPrice + queryString, true);
ajaxRequest.send(null);
<?php foreach ($productPrices as $price): ?>
name[k] = "<?php echo $price['Product']['txtname']; ?>";
model[k] = "<?php echo $price['Product']['txtmodel']; ?>";
k++;
<?php endforeach; ?>
k=0;
for (var i = 0; i < product.length; i++) {
k = product.options[i].value;
if (product.options[i].selected) {
output += '<tr>'+
'<td style="border-right: 0px; width:270px; text-align:center" id="ProductProduct'+k+'" name="data[Product][Product]['+k+']">'+name[i]+'</td>'+
'<td style="border-right: 0px; width:100px; text-align:left" id="ProductProduct'+k+'" name="data[Product][Product]['+k+']">'+model[i]+'</td>'+
'</tr>';
}
}
output = '<table style="width:500px; border: 0px;">'+output+'</table>';
document.getElementById('productTable').innerHTML = output;
}
</script>
You need some kind of repeated AJAX check in your page to see if there is new data in the database. You can do this using setTimeout or setInterval.
E.g.
function CheckData() {
List();
setTimeout(CheckData, 10000);
}
setInterval(function() {
List(); // your function
// Do something every 2 seconds
}, 2000);
this is jquery function this will help you.

Form Inputs updated via JS don't get submitted

The invoice input values which hold the totals of invoice line items that get updated via JS return a NULL value when they are submitted.
<span class="sublabel">Subtotal</span><input type="text" class="total-box" id="product-subtotal" readonly="true" />
<span class="sublabel">Tax</span><input type="text" class="total-box" id="product-tax" readonly="true" />
<span class="sublabel">Total</span><input type="text" class="total-box" id="order-total" readonly="true" />
The JS
function calcProdSubTotal() {
var prodSubTotal = 0;
$(".row-total-input").each(function(){
var valString = $(this).val() || 0;
prodSubTotal += parseInt(valString);
});
$("#product-subtotal").val(prodSubTotal);
};
function calcTaxTotal() {
var taxTotal = 0;
//var taxAmount = 10;
var taxAmount = $("#salesTaxAmount").val() || 0;
var productSubtotal = $("#product-subtotal").val() || 0;
var taxTotal = parseInt(productSubtotal) * parseInt(taxAmount) / 100;
var taxTotalNice = taxTotal;
$("#product-tax").val(taxTotalNice);
};
function calcOrderTotal() {
var orderTotal = 0;
var productSubtotal = $("#product-subtotal").val() || 0;
var productTax = $("#product-tax").val() || 0;
var orderTotal = parseInt(productSubtotal) + parseInt(productTax);
var orderTotalNice = "$" + orderTotal;
$("#order-total").val(orderTotalNice);
};
$(function(){
$('.row-total-input').each(
function( intIndex ){
$('.invAmount').livequery('blur', function() {
var $this = $(this);
var amount = $this.val();
var qty = $this.parent().find('.invQty').val();
if ( (IsNumeric(amount)) && (amount != '') ) {
var rowTotal = qty * amount;
$this.css("background-color", "white").parent().find(".row-total-input").val(rowTotal);
} else {
$this.css("background-color", "#ffdcdc");
};
calcProdSubTotal();
calcTaxTotal()
calcOrderTotal();
});
}
);
});
I originally had the inputs set as disabled however I have changed them to readonly because disabled fields can't be submitted.
What am i missing?
Thanks in advance.
You haven't set a name-attribute on your <input />s, so PHP can't access their values, and returns nothing when you look for $_POST['product-tax']. If you have set error_reporting to E_ALL, you should see a notice telling you you are trying to access an undefined index on the $_POST array.

Categories