<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
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 have a table with a button that adds 5 rows with cells to the table when clicked. I want to bind an event to cells in the 5th column of the table. All of these cells are named "Count_" followed by the row number. So, the cell in Row 0 is:
<td name="CountCell_0">
<input type="text" name="Count_0">
</td>
And I'm trying to update the input with name Count_X (where X is the row number).
The binding works for the cells that existed on the page originally. However, the event is not triggering for cells that were added with the button.
Here is an example of a cell that was dynamically added:
<td>
<input type="text" name="Count_348">
</td>
Here is my Jquery event:
$(document).ready(
function() {
$(document).on('change','[name^="Count_"]',function() {
console.log('here'); //not triggering on dynamic cell
var cell = $(this).attr('name');
var idx = cell.split('_')[1];
var amount = $(this).val() * $('[name="AvgCost_' + idx + '"]').html();
$('#ExtendedCostCell_' + idx).html(amount.toFixed(2));
});
}
);
I think the problem was here [name^="Count_"]' you need a selector so change to this input[name^="Count_"]' and the anonimous function is not performed
$(document).ready(
(function() {
$(document).on('change','input[name^="Count_"]',function() {
console.log('here'); //not triggering on dynamic cell
var cell = $(this).attr('name');
var idx = cell.split('_')[1];
var amount = $(this).val() * $('[name="AvgCost_' + idx + '"]').html();
$('#ExtendedCostCell_' + idx).html(amount.toFixed(2));
});
}());
);
I moved the function outside of the document ready, and it now triggers on the dynamic rows.
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'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/
I have a search box. I'm using jQuery and keyup to filter repeating divs.
Each div looks like this:
<div class="searchCell" id="searchCell' . $id . '">';
<div class="friendName">
// someNameOutputWithPHP.
</div>
</div>
Now, I want to filter based on the name text. If someNameOutputWithPHP contains the search query, the entire searchCell should show(). If it doesn't, the entire searchCell should hide().
This doesn't work, though:
<script type="text/javascript">
$(document).ready(function() {
$("#searchbox").keyup(function() {
var searchValue = $(this).val();
if(searchValue === "") {
$(".searchCell").show();
return;
}
$(".searchCell").hide();
$(".searchCell > .friendName:contains(" + searchValue + ")").show();
});
});
</script>
EDIT
New problem: I got the divs show() to show how I want. But the :contains isn't working exactly right.
For instance: say one of the name's is Ryan. When I search for 'Ryan', I get nothing. But when I search for 'yan' I get the Ryan div.
What's wrong?
Here's the :contains code:
$(".friendName:contains(" + searchValue + ")").parent().show();
That is because you are hiding the .searchCell and then showing its children .friendName divs, which though get display property will not show up because parent is hidden.
Try this:
<script type="text/javascript">
$(document).ready(function() {
$("#searchbox").keyup(function() {
var searchValue = $(this).val();
if(searchValue === "") {
$(".searchCell").show();
return;
}
$(".searchCell").hide();
//$(".searchCell:has(.friendName:contains(" + searchValue + "))").show();
// OR
//$(".friendName:contains(" + searchValue + ")").parents(".searchCell").show();
// OR
$(".friendName:contains(" + searchValue + ")").parent().show(); // If .searchCell is always a direct parent
});
});
</script>
Your selector
$(".searchCell > .friendName:contains(" + searchValue + ")")
will select all .friendName divs that contain the text from searchValue. That works just fine, but you need to .show() the parent element. Just invoke the .parent() method for that:
$(".searchCell > .friendName:contains(" + searchValue + ")").parent().show();
Demo: http://jsfiddle.net/d3ays/3/
And by the way, you HTML markup looks messed up too. There is a ; behind your div.searchCell for instance.