I've been working in a project where I need to dynamically fill a table according with what I select from two combobox, so the problem is that I need to take those values to save them on the database but I can't find a way to do this.
The code when I press the button:
<input type="button" name="btnAgregarPrograma" value="Agregar" onClick="addRow()"/>
function addRow()
{
var dep = $("#cbxDependencia").val();
var pro = $("#cbxPrograma").val();
if(dep == 0 || pro == 0)
alert('Debe seleccionar una dependencia y un programa para poder agregarlos'); //Traslation: you must select a dependency and a program to continue
else
{
$.get("funciones/agregarProDep.php",{pro: pro},
function(resultado)
{
if(resultado == false)
{
alert("Error");
}
else
{
$("#table_depProg").attr("disabled",false);
var row = $("<tr>" + resultado + "</tr>");
$('#table_depProg').append(row);
}
}
);
}
}
As you can see, the code above calls a php file with the next code
<?php
include("funciones.php");
$pro = 0;
$programas = agregarProgramaDependencia($_GET["pro"]);
foreach($programas as $fila)
{
echo ("
<td id=".$fila['idPrograma'].">".$fila['Nombre']."</td>
<td><input type='button' value='Eliminar' onclick='borrarFila(this)'</td>
");
}
?>
That's the way I fill the table, but now I just can't find a way to get the contained data when I submit the page to get and save the data, I would apreciate any help.
I tried to explain the best I could, if something is not clear just let me know and I will answer back with a better explanation.
I know this is an old question, but I ran into the same thing and here is what I did.
Created a DataRow object that contained the fields of each row
Iterated through the table's rows (skipping the header) and stored each row in a DataRow and pushed it onto an Array.
Used JSON.Stringify to convert the Array to JSON
Stored the JSON in a <input type="hidden"> so it would get POSTed.
Here is the HTML example:
<table border="2px solid black">
<tr id="header-row">
<th>Dx Code</th>
<th>Dx Date</th>
<th>OnSet Or Ex</th>
</tr>
<tr>
<td>3022</td>
<td>1/1/2014</td>
<td>ONSET</td>
</tr>
<tr>
<td>V9099</td>
<td>1/21/2014</td>
<td>EX</td>
</tr>
<tr>
<td>1199</td>
<td>1/31/2014</td>
<td>ONSET</td>
</tr>
</table>
<br />
<input type="button" value = "Submit" id="out">
JavaScript:
// object to hold your data
function dataRow(value1,value2,value3) {
this.dxCode = value1;
this.dxDate = value2;
this.dxType = value3;
}
$('#out').click(function(){
// create array to hold your data
var dataArray = new Array();
// iterate through rows of table
// * Start from '2' to skip the header row *
for(var i = 2; i <= $("table tr").length; i++){
// create object and push to array
dataArray.push(
new dataRow(
$("table tr:nth-child(" + i + ") td").eq(0).html(),
$("table tr:nth-child(" + i + ") td").eq(1).html(),
$("table tr:nth-child(" + i + ") td").eq(2).html())
);
}
var sJson = JSON.stringify(dataArray);
alert(sJson);
})
Finally, JSFiddle to see it: http://jsfiddle.net/leisenstein/vy3ux/
Related
I have a table as the following datatable table :
<button id="addRow">Add New Row</button><br>
<table class="table table-striped table-bordered table-hover " id="example" cellSpacing=0 width="100%">
<thead>
<tr>
<th>1</th>
<th>2</th>
<th>3</th>
<th>4</th>
<th>5</th>
</tr>
</thead>
<tr style="text-align: center;">
<td>hola</td>
<td>ciao</td>
<td>bonjour</td>
<td>yo</td>
<td>salut</td>
</tr>
</table>
I'd like to append elements using a javascript script as the following :
<script type="text/javascript">
$(document).ready(function () {
debugger;
var t = $('#example').DataTable({ "searching": true, "paging": true });
var counter = 1;
$('#addRow').on('click', function ciicici() {
var now = new Date();
var now = now.toMysqlFormat();
var tii = new Date();
tii.setSeconds(tii.getSeconds() - 50000);
var tii = tii.toMysqlFormat();
$.post( "sqlmachine_test_ajax.php", { timing: now,seconding: tii })
.done(function( data ) {
t.row.add([
counter +'.1',
counter +'.2',
counter +'.3',
counter +'.4',
counter +'.5'
]).draw();
counter++;
// });
//setTimeout(function(){ciicici();}, 5000);
}); // Automatically add a first row of data
$('#addRow').click();
});
</script>
The two are working properly, the only thins is that I'd like to retreive the elements to append trough an Jquery AJAX script.
Let's say I have a php page sending back 5 values I'd like to add to each column (instead of the counter1, counter2 etc...) as the following :
<?php
echo 'counter1, counter2, counter3, counter4, counter5';
?>
and in the javascript I wanted to put simply :
...
.done(function( data ) {
t.row.add([
data //(instead of the counters)
]).draw();
counter++;
...
I have tried this, as well as arrays and json encoded arrays, but all I get is the 5 results in the same first cell of the table.
So how could I append the ajax php response to a table as data in different cells of the table?
marko
When you get your data back from the call, you have to separate using .split().
so you can do this when you get your callback
.done(function( data ) {
var splitData = data.split(", ") //Split your data with the comma and space
$.each(splitData, function(e){ //For each piece of data
//Add your rows here one by one
t.row.add([
splitData[e] //Make sure the 'e' in the function and here are the same
]).draw();
})
counter++;
});
This a loose answer, I'll try to add more soon.
Edit: More info
what I normally do is echo everything with separators. So, in your case, I would echo 1, 2, 3, 4, 5:A, B, C, D, E. So when the data returns, that's what you'll see.
In your data success, you would do something like
var dataParts = data.split(":") //This splits your data into the 2 parts using the : separator
var dataPart1 = dataParts[0] //This will get 1, 2, 3, 4, 5
var dataPart2 = dataParts[1] //this will get A, B, C, D, E
Then from there, you split using commas.
var dataPieces1 = dataPart1.split(', ');
var dataPieces2 = dataPart2.split(', ');
Then run the loops. (using javascript's for loop is usually better than using jQuery's .each())
for(var i = 0; i < dataPieces1.length; i++){ //Start your for loop on the first part
//Create a row here using dataPieces1[i], this will loop and make a new
//row every time the next loop finishes
for(var j = 0; j < dataPieces2.length; j++){ //Start the second loop
//Not sure how you would want to do this, but here's some example code
//Since you're inside a row now, append your dataPieces2[j] to that row
//This will loop for every dataPieces2 and append each one as a column
//in that single row.
}
}
I've got a script on my website which checks for new database entries every second and updates puts them into a table.
I'm having a problem where the script is deleting the table headers from the page. They still appear in the source code (Right clicking and displaying page source), but they don't appear visible to the user.
The problem seems to lie within "while (tbl.lastChild != tbl.firstChild) { tbl.removeChild(tbl.lastChild); }", but if I remove this line of code, the script will continuously display the same data, over and over again. For example, if I have name 1, name 2 and name 3 in the database. All three will be displayed, and then repeated.
How can I display the table headers, while stopping the data from repeating?
My full script code is:
function tick() {
var xhttp = new XMLHttpRequest();
xhttp.onload = (function() {
var data = JSON.parse(xhttp.responseText);
var tbl = document.getElementById("reports");
while (tbl.lastChild != tbl.firstChild) { tbl.removeChild(tbl.lastChild); }
function cell(data) {
var c = document.createElement("td");
c.appendChild(document.createTextNode(data));
return c;
}
for (var i = 0; i < data.length; i++) {
var row = document.createElement("tr");
row.appendChild(cell(data[i]["id"]));
row.appendChild(cell(data[i]["firstname"]));
row.appendChild(cell(data[i]["lastname"]));
row.appendChild(cell(data[i]["date"]));
var a = document.createElement("a");
var c = document.createElement("td");
a.href = "view.php?id=" + data[i]["id"];
a.appendChild(document.createTextNode("View ID"));
c.appendChild(a);
row.appendChild(c);
tbl.appendChild(row);
setTimeout(tick, 1000);
}
});
xhttp.open("GET", "reportload.php", true);
xhttp.send("");
}
addEventListener("DOMContentLoaded", function() {
tick();
});
You can try create next html table and use it:
<table>
<thead>
<tr>
<th>title1</th>
<th>title1</th>
</tr>
</thead>
<tbody id="reports">
<tr>
<td>value</td>
<td>value</td>
</tr>
</tbody>
</table>
The childern of the HTML node are not only TRs, but also any portion of whitespaces between them, so Your loop probably deletes all TRs and leaves only the first portion of whitespaces.
I would suggest to put header in THEAD and data rows in TBODY and then operate only on TBODY, leaving the header intact.
I have php code that creates a table. For each item on the purchase order a new row is created and populated. The goal is when the purchase order is edited it gets posted back and saved in the database. Everything is working except my jQuery code will only iterate over the first row for however many rows I have. (So if I have three rows it will print the first rows cartid three times.)
Sorry if things look messy.
PHP Code:
<?php while($row = mysql_fetch_array($itemsquery)){?>
<tr class="item-row" id="<?php echo $row['cart_id']?>">
<td class="item-name"><div class="delete-wpr"><textarea><?php echo $row['on0'];?> <?php echo $row['itemname'];?></textarea><a class="delete" href="javascript:;" title="Remove row">X</a></div></td>
<td class="description"><textarea class="cartid"><?php echo $row['cart_id'];?></textarea></td>
<td><textarea class="cost" class="text-input" type="text"><?php echo $row['itemprice'];?></textarea></td>
<td><textarea class="qty" type="text" name="name"><?php echo $row['quantity'];?></textarea></td>
<td><span class="price" type="text">$<?php
$linecost = $row['quantity'] * $row['itemprice'];
echo $linecost;?></span></td>
</tr>
<?php }?>
jQuery statement to see what it has grabbed:
$(document).ready(function(){
$(".item-row").change(function() {
$((".cartid")).each(function(){
row = {
cartid: $(".cartid").val()
}
alert(row.cartid);
performAjaxSubmission();
})
});
It looks like you just have your selectors mixed up. You are wanting to iterate over each of the rows, but your selector is referencing $(".cartid"), which would always return the first result ever time.
This should fix your problem:
$(document).ready(function(){
$(".item-row").change(function() {
$(".item-row").each(function(){
var rowContext = $(this);
var row = {
cartid: $(".cartid", rowContext).val()
}
alert(row.cartid);
performAjaxSubmission();
});
});
You have extra () in your .cartid selector.
$(document).ready(function(){
$(".item-row").change(function() {
$(".cartid").each(function(){
row = {
cartid: $(".cartid").val()
}
alert(row.cartid);
performAjaxSubmission();
})
});
Also, shoudn't you be looping trough .item-row instead of .cartid?
You're iterating like this:
$(".cartid").each(function(){
row = {
cartid: $(".cartid").val()
}
Seems like you should be doing
$(".cartid").each(function(){
row = {
cartid: $(this).val()
}
Haven't checked the rest of the code.
EDIT:
$(".cartid").each(function(){
var cart = $(this);
row = {
cartid: cart.val()
}
I'm making a site for myself, and I'm trying to implement some javascript for instant calculations, but I'm having some issues:
Is there any way I can avoid typing
level_prices["3"]=3;
level_prices["4"]=4;
... etc. up to 90: in other words, is there any way I can do like I did in the PHP code and make it create this value until 90, which looks a lot cleaner?
Why is this returning $Undefined? I suspect that it's not getting the value from the HTML form, but the code looks correct ...
Here is my code:
relevant HTML/PHP:
<form action="" id="priceCalcForm" onsubmit="return false;">
<table class="table">
<tbody>
<tr> <!-- first row, with css -->
<td style="width:50%;">
<select name="fromlevel" id="fromlevel" onchange="calculateTotal()" style="width:100%; text-align:center; font-weight:bold;">
<option value="none" name="none">0</option>
<?php
$i = 1;
while ($i < 91) {
echo '
<option value=' . $i . ' name=' . $i . '>' . $i . '</option>';
$i++;
}
?>
</select>
</td>
</tr>
</tbody>
</table>
</form>
Included JS:
var level_prices= new Array();
level_prices["None"]=0;
level_prices["1"]=1;
level_prices["2"]=2;
function getLevelPrice()
{
var levelSetPrice=0;
//Get a reference to the form id="cakeform"
var theForm = document.forms["priceCalcForm"];
//Get a reference to the select id="filling"
var selectedLevel = theForm.elements["fromlevel"];
//set cakeFilling Price equal to value user chose
//For example filling_prices["Lemon".value] would be equal to 5
levelSetPrice = level_prices[selectedLevel.value];
//finally we return cakeFillingPrice
return levelSetPrice;
}
function calculateTotal()
{
//Here we get the total price by calling our function
//Each function returns a number so by calling them we add the values they return together
var LevelPrice = getLevelPrice();
var divobj = document.getElementById('totalPrice');
divobj.style.display='block';
divobj.innerHTML = "Total Price For the Leveling $"+LevelPrice;
}
function hideTotal()
{
var divobj = document.getElementById('totalPrice');
divobj.style.display='none';
}
I consider myself decent with PHP, but its first time I am using JS.
1) use a loop:
var level_prices = {}; // object literal not array!
level_prices['none'] = 0;
for(var i = 1; i <= 90; i++ ) {
level_prices[i] = i;
}
the first to lines could also be written like this (already define the none-property):
var level_prices = {'none': 0};
2) level_prices is not an array it is an object-literal (see part 1 of my answer)
see a working fiddle here: http://jsfiddle.net/BkGxq/
(also notice that i deleteted the inline onchange handler from your markup and put it to the javascript (at the bottom)
Yes. Any variable in PHP (except Resource-type variables) can be dumped directly into JavaScript with json_encode.
<html>
<head>
<script src="jquery-1.4.4.js"></script>
<script>
$('table').each(function(a, tbl) {
var currentTableRows = $(tbl).attr('rows').length - 1;
$(tbl).find('th').each(function(i) {
var remove = 0;
var currentTable = $(this).parents('table');
var tds = currentTable.find('tr td:nth-child(' + (i + 1) + ')');
tds.each(function(j) { if (this.innerHTML == '') remove++; });
if (remove == currentTableRows) {
$(this).hide();
tds.hide();
}
});
});
</script>
</head>
<body>
<table border="1" >
<tr><td colspan="4" > alaa </td></tr>
<tr><th>Column1</th><th>Column2</th><th>Column3</th><th>Column4</th></tr>
<tr ><td>1st</td><td>1.1</td><td></td><td></td></tr>
<tr class="data"><td>2nd</td><td>2.1</td><td></td><td></td></tr>
<tr class="data"><td>3rd</td><td>3.1</td><td></td><td>1</td></tr>
<tr class="data"><td>4th</td><td></td><td></td><td></td></tr>
<tr ><td></td><td></td><td></td><td></td></tr>
<tr class="data"><td></td><td></td><td></td><td></td></tr>
</table>
</body>
here is my code ... I thought that the problem from the library, so I tried many libraries such as jQuery 1.4.4 , 1.5.2 and others
Here is the test and it works fine there http://jsfiddle.net/nlovatt/JsLn8/
but in my file .. it doesn't work ..
regards,
There are two reasons your code isn't working.
1) You're executing the script immediately upon loading of the HEAD, at this stage, your table doesn't exist and so it does nothing. To fix this, make sure you execute it on page load instead.
2) When you're comparing the number of blank cells in the column with the number of total rows in the table, you're missing the fact that most of your columns don't have the same number of rows as the table (your first row is only one column wide). You need to compare to the number of rows in the actual column, or better yet, just do the reverse thing and check for non-empty columns.
The full code then becomes:
$(document).ready(function() {
$('table').each(function(a, tbl) {
$(tbl).find('th').each(function(i) {
var remove = true;
var currentTable = $(this).parents('table');
var tds = currentTable.find('tr td:nth-child(' + (i + 1) + ')');
tds.each(function(j) { if (this.innerHTML != '') remove = false; });
if (remove) {
$(this).hide();
tds.hide();
}
});
});
});
try it like this
$('#mytable tr th').each(function(i) {
//select all td in this column
var tds = $(this).parents('table')
.find('tr td:nth-child(' + (i + 1) + ')');
//check if all the cells in this column are empty
if(tds.length == tds.filter(':empty').length) {
//hide header
$(this).hide();
//hide cells
tds.hide();
}
});
for hiding columns in table if all cells in column are empty