Search data from multiple columns in table - javascript

I have made a table that outputs data from a database. I added a searchbar that works for 1 column, but my goal is to make it work for two columns in the table: The 'Locatie' column and the 'Nr.' column. Besides that (but less important) I would like the thead to stay visible when something is searched. Right now it disappears and only shows the data that is searched for.
My code is as following:
<script>
function myFunction() {
var input, filter, table, tr, td, i;
input = document.getElementById("myInput");
filter = input.value.toUpperCase();
table = document.getElementById("myTable");
tr = table.getElementsByTagName("tr");
for (i = 0; i < tr.length; i++) {
td = tr[i].getElementsByTagName("p")[0];
if (td) {
if (td.innerHTML.toUpperCase().indexOf(filter) > -1) {
tr[i].style.display = "";
} else {
tr[i].style.display = "none";
}
}
}
}
</script>
<div class="titel-top">
<div class="col-xs-10">
<div class="input-group">
<input type="text" class="form-control" id="myInput" placeholder="Zoeken naar locatie..." onkeyup="myFunction()">
<!--<span class="input-group-btn">
<button class="btn btn-secondary" type="button">Zoeken</button>
</span>-->
</div>
</div>
</div>
<?php
$page_title = "Sensors";
?>
<div class="row">
<table class="table" id="myTable">
<thead>
<tr>
<th><p class="text-14">Status</p></th>
<th><p class="text-14">Locatie</p></th>
<th><p class="text-14">Nr.</p></th>
<th><p class="text-14">Sensors</p></th>
<th></th>
</tr>
</thead>
<tbody>
<tr>
<td><div id="status"></div></td>
<td><p class="text-12"><?php echo $locatie ?></p></td>
<td><p class="text-12"><?php echo $huisnummer ?></p></td>
<td><p class="text-12">5</p></td>
<td class="meer-informatie-verhuurder"><svg class="chev-forward" viewBox="0 0 24 24">
<path d="M8.59,16.58L13.17,12L8.59,7.41L10,6L16,12L10,18L8.59,16.58Z" />
</svg></td>
</tr>
</tbody>
</table>
</div>
<?php
//bekijkt of één van de waardes rood is.
if($co2 >1000 OR $humidity >80 OR $temperature >25 OR $temperature <9 OR $humidity <30) {
?>
<script>
document.getElementById("status").style.backgroundColor = "#ff1744";
</script>
<?php
//bekijkt of één van de waardes oranje is.
}
elseif ($co2 >800 OR $humidity >60 OR $temperature >20 OR $temperature >9 OR $humidity >30) {
?>
<script>
document.getElementById("status").style.backgroundColor = "#dc9b10";
</script>
<?php
//Als er geen rode of oranje status is wordt de status groen.
}else { //maakt status groen.
?>
<script>
document.getElementById("status").style.backgroundColor = "#51c53f";
</script>
<?php
}
?>
The table can be found on the website: http://st359450.cmd17c.cmi.hanze.nl/senz/verhuurder-sensors.php
You will need to log in: username '1' and password 'Hallo'
I include the header, footer etc. at the top and bottom of the page, I didn't think they would be relevant for this question. I hope you guys can help me.

td = tr[i].getElementsByTagName("p")[0];
In this line, as you access the element at index 0 in the returned list of <p> elements, you are incidentally getting the values from "Locatie" column.
A quick fix would be to read the value from element at index 1 as well, and show the tr element if either of them contain given word:
var paragraphsInRow = tr[i].getElementsByTagName("p");
var locatie = paragraphsInRow[0];
var nr = paragraphsInRow[1];
if (locatie || nr) {
if (locatie.innerHTML.toUpperCase().indexOf(filter) > -1
|| nr.innerHTML.toUpperCase().indexOf(filter) > -1) {
tr[i].style.display = "";
} else {
tr[i].style.display = "none";
}
}
Possible improvements:
Don't filter using innerHTML. As evident from the name, it returns the HTML content of the paragraph element. Currently that paragraph element may not contain HTML elements, but in future it might. So it is best to use innerText for filtering data - which only contains the visible text within the element.
Instead of identifying data through tr[i].getElementsByTagName("p")[0], use a better CSS selector. I would suggest setting a CSS class in the HTML, and then using a descendant selector like tr[i].querySelector("p.locatie"). Your HTML should then look like:
<tr>
<td><div id="status"></div></td>
<!-- Notice the CSS class added here. -->
<td><p class="text-12 locatie"><?php echo $locatie ?></p></td>
<td><p class="text-12"><?php echo $huisnummer ?></p></td>
<td><p class="text-12">5</p></td>
<td class="meer-informatie-verhuurder"><svg class="chev-forward" viewBox="0 0 24 24">
<path d="M8.59,16.58L13.17,12L8.59,7.41L10,6L16,12L10,18L8.59,16.58Z" />
</svg></td>
</tr>
Doing so would make it easier to change the markup in future. For instance, if you add another column between "Status" and "Locatie", an index based selector would give incorrect results.

Related

treeview not working properly in html table

I have the following table in html:
<div class="col-lg-12 grid-margin stretch-card">
<div class="card">
<div class="card-body">
<h4 class="card-title" id="section-title">
{{$inventory_name}} - {{ $category_name }}
</h4>
<div class="table-responsive">
<table class="table table-striped" id="medstable">
<thead>
<tr class="header">
<th>
Nume
</th>
#if ($inventory_id == 1 || $inventory_id == 2)
<th>Cantitate Totala</th>
#endif
</tr>
</thead>
<tbody>
#if( !empty($items) )
#php
$i = 0;
#endphp
#foreach ($items as $item)
<tr data-count="{{ $loop->index }}">
<td> {{$item->name}}</td>
#if ($inventory_id == 1)
<td>150 / {{$minimum_quantities_farm[$i]->quantity ?? 0}}</td>
#php
$i++;
#endphp
#endif
#if ($inventory_id == 2)
<td>150 / {{$minimum_quantities_stoc3[$i]->quantity ?? 0}}</td>
#php
$i++;
#endphp
#endif
</tr>
<tr class="treeview tr-{{ $loop->index }}">
<td colspan="100%">
<table>
<thead>
<tr>
#if ($item->category_id == 1)
<th>Cod CIM</th>
#endif
<th>Cod Produs</th>
<th>Cantitate</th>
<th>Termen Valab</th>
<th>Lot</th>
<th>UM</th>
<th>Pret Unitar</th>
<th>TVA</th>
<th>Pret TVA</th>
</tr>
</thead>
<tbody>
#if( !empty($item_stock[$item->name]))
#foreach($item_stock[$item->name] as $inItem)
#if($inItem['quantity'] > 0)
<tr>
#if ( $inItem['category_id'] == 1)
<td>{{$inItem['cim_code']}}</td>
#endif
<td>{{$inItem['product_code']}}</td>
<td>{{$inItem['quantity']}}</td>
#if ((new \DateTime($inItem['exp_date']))->format('Y-m-d') > (new \DateTime())->format('Y-m-d'))
<td>{{$newDate = date("d-m-Y", strtotime($inItem['exp_date'])); }}</td>
#else
<td style="color:red; font-weight: bold;">EXPIRED</td>
#endif
<td>{{$inItem['lot']}}</td>
<td>{{$inItem['m_name']}}</td>
<td>{{$inItem['price']}}</td>
<td>{{$inItem['tva']}}</td>
<td>{{$inItem['tva_price']}}</td>
</tr>
#endif
#endforeach
#endif
</tbody>
</table>
</td>
</tr>
#endforeach
#endif
</tbody>
</table>
</div>
</div>
</div>
</div>
I also have this input bar in which I can search through the table's items:
<input type="text" id="myInput" onkeyup="myFunction()" placeholder="Search..">
Below is the JavaScript myFunction() function:
function myFunction() {
let input, filter, table, tr, td, i, txtValue;
input = document.getElementById("myInput");
filter = input.value.toUpperCase();
table = document.getElementById("medstable");
tr = table.getElementsByTagName("tr");
for (i = 0; i < tr.length; i++) {
td = tr[i].getElementsByTagName("td")[0];
if (td) {
txtValue = td.textContent || td.innerText;
if (txtValue.toUpperCase().indexOf(filter) > -1) {
tr[i].style.display = "";
} else {
tr[i].style.display = "none";
}
}
}
}
The thing is, whenever I click on a row, the row should expand and display the values that are basically hidden (until I press on a row). It works fine, but for example, if I search for an item and I find it, if I click on it, the row will not expand anymore. How can I solve this? I also have this JavaScript function that basically expands the row:
function treeviewDisplay() {
jQuery('#medstable tbody tr:not(.treeview)').click(function() {
const treeview = jQuery('#medstable tbody tr.treeview.tr-' + jQuery(this).data('count'));
if( treeview.hasClass('active') ) {
treeview.removeClass('active');
} else {
jQuery('#medstable tbody tr.treeview').removeClass('active');
treeview.addClass('active');
}
});
}
And the css:
tr.treeview {
display:none;
transition: 0.5 all;
}
tr.treeview.active{
display: table-row;
}
tr.treeview table{
width: 100%;
}
P.S: I left the embedded php in the table, maybe it will help. If not, I can change to some hardcoded data
EDIT: I read the question again and I thought I should explain in better. So, if I don't search for anything, on any item I would click, the row expands with the data. However, if I search for the second item for example, the table is gonna show only the second item. And if I click on it, it won't expand. The rows only expand when you don't search for anything. I want them to expand even if I search for something

how can calculate row in table by javascript

Here is my Code :
<html>
<body>
<table id="my Table">
<tbody>
<tr>
while($row = mysqli_fetch_assoc($result))
<td>
<?php echo $row['ItemQTY']; ?>
</td>
</tr>
<tr class="total Column">
<td class="tota Column">Total:</td>
</tr>
</tbody>
</table>
</body>
</html>
I want to make the last row in the table sum of ItemQTY
this java to search in the table
function myFunction() {
// Declare variables
var input, filter, table, tr, td, i;
input = document.getElementById("myInput");
filter = input.value.toUpperCase();
table = document.getElementById("myTable");
tr = table.getElementsByTagName("tr");
// Loop through all table rows, and hide those who don't match the search query
for (i = 0; i < tr.length; i++) {
td = tr[i].getElementsByTagName("td")[0];
if (td) {
if (td.innerHTML.toUpperCase().indexOf(filter) > -1) {
tr[i].style.display = "";
} else {
tr[i].style.display = "none";
}
}
}
}
but this script not calculate total qty
how can add calculate row with this code
Sum up the values in PHP and store it in variable. Then just print it in Total row.
$totalQty = 0;
while($row = mysqli_fetch_assoc($result))
{
$totalQty += $row['ItemQTY'];
?>
<td>
<?php echo $row['ItemQTY']; ?>
</td>
<?php
} ?>
<tr class="total Column">
<td class="tota Column">Total: <?php echo $totalQty;?></td>
</tr>
If your HTML page contains only one table then you can get count of <tr> tags.
You will get total rows in the table then subtract the last row ( i.e. 1 row for showing total) from your total count. You can get count of <tr> tag in JavaScript as follows:
var rowCount = document.getElementsByTagName("tr").length - 1;

Delete and Update dynamically created Table row ID's serially using Jquery

For example I am listing products for sale using ajax, jquery on Table. Where every table row are getting dynamic id's like, row_1, row_2, row_3 etc.
There is an option to remove any of rows, for example second row(row_2) is removed.
So what I want is, after the row gets deleted, the table row id's should get update also, probably a function will do it, for example I don't want it to be row_1, row_3 instead I want it to be row_1, row_2.
I'd this code already with me somewhere in my project, tweaked little but as per your need.
Jquery part
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script>
$(document).ready(function(){
$(".remove_tr").click(function(){
var tr_id = $(this).parent().attr("id");
var flag = "N"; var row_cnt = 0;
$("#dummy_table tr").each(function(){
if( flag == "Y" ){
$(this).attr("id", "row_"+ row_cnt);
$(this).children("td:first-child").html("row_"+ row_cnt);
$(this).attr("id", "row_"+ row_cnt);
row_cnt++;
}
if( flag =="N" && $(this).attr("id") == tr_id){
var rowArr = $(this).attr("id").split("_");
row_cnt = rowArr[1];
$(this).remove(); flag= "Y";
}
})
});
});
</script>
HTML part
<table id="dummy_table">
<?php for($i = 0; $i < 10; $i++){ ?>
<tr id="row_<?php echo $i; ?>">
<td>row_<?php echo $i; ?></td>
<td class="remove_tr">remove</td>
</tr>
<?php } ?>
</table>
Let me know if it works for you
It's simple. Run code snippet below.
$(".remove").click(function() {
$(this).parent().remove();
var counter = 1;
$("#foo tr").each(function() {
$(this).attr('id', 'row_'+counter);
$(this).find('td:first-child').html('row_'+counter); //just to show the result
counter++;
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<table id="foo">
<tr id="row_1" class="block" >
<td>row_1</td>
<td class="remove">remove</td>
</tr> <br>
<tr id="row_2" class="block" >
<td>row_2</td>
<td class="remove">remove</td>
</tr> <br>
<tr id="row_3" class="block" >
<td>row_3</td>
<td class="remove">remove</td>
</tr> <br>
<tr id="row_4" class="block" >
<td>row_4</td>
<td class="remove">remove</td>
</tr> <br>
</table>

Using Javascript How to loop through a div containing checkboxes and get the value checked from each check box

I have a table with each row containing a cell that has 8 check boxes(Column4)
Here is an example
<table id="enc-assets" class="table">
<thead>
<tr><th>Column1</th><th>Column2</th><th>Column3</th><th>Column4(CONTAINS OPTIONS)</th>
</thead>
<tbody>
<tr>
<td id="sc-isrc"></td>
<td id="sc-filename"></td>
<td id="sc-path" hidden></td>
<td id="sc-platforms">
<div id="sc-inline" style="display: inline-block;">
<div >
<div ng-repeat="p in products ">
<label id="enc"><input id="Platform" ng-checked="prod[p.name]" ng-model="prod[p.name]" ng-init="prod[p.name] = true" type="checkbox"/></label>
</div>
</div>
</div>
</td>
<td>
</td>
<td><br/><br/><button id="enqueuebtn" type="button" ng-click="Show(test)" class="btn-primary"></button></td>
</tr>
</tbody>
</table>
I am trying to loop through each row and assign values from each cell into an object .
I am having problems getting the value checked from the cell that contains the 8 check boxes. I can get values from the other cells just fine.
I have tried the following:
$("#enc-assets tbody tr").each(function() {
var message;
message = new Object();
message.isrc = $(this).find('#sc-isrc').text();
message.path = $(this).find('#sc-path').text();
$("#sc-platforms div div").each(function() {
var platform, selected;
selected = $(this).find('#Platform div label input').checked;
if (selected === true) {
platform = $(this).find('#enc').text();
This is the part that I am not sure if works:
selected = $(this).find('#Platform div label input').checked;
Do I have the correct nesting here to get the values from the check boxes?
Try this:
jsFiddle here
$("#enc-assets tbody tr").each(function() {
var message;
message = new Object();
message.isrc = $(this).find('#sc-isrc').text();
message.path = $(this).find('#sc-path').text();
$("#sc-platforms>div>div").each(function() {
alert( $(this).attr('id') );
var platform, selected;
selected = $(this).find('#Platform');
if(selected.is(':checked')) {
alert('Checked');
}
platform = $(this).find('#enc').text();
alert(platform);
}); //END each #sc-platforms>div>div
}); //END each #enc-assets tbody tr

How to grab the values from an HTML table's cells using JavaScript

I'm trying to grab the cell values from an HTML table so that I can save them into a MySQL table via a call to PHP. I'd like to use JavaScript rather than jQuery.
I'm giving each TR a distinct ID based on the MySQL table's ID field. Also, each TD input cell has a unique ID based on the MySQL table's ID field. Not sure if I need all those, but I used them.
How do I grab the cell's value so that I can pass it to a PHP procedure(I know how to code this PHP) to save the data into MySQL? My JavaScript code below grabs the "innerHTML" but I need to grab the cell value's instead.
For example, if I have 3 rows of data from a MySQL table, with fields id and amount, with values below, how do I grab the "3" and the "1.99"?:
id amount
-------------
1 100.00
2 9.99
3 1.99
Here is a sample of the PHP/HTML code for the table, submit button and onclick call:
(this is a very simplified version of my actual code but should convey the idea)
<?php
/* define mysql database connect, query and execute it returning result set into $result, id=integer primary key, is_active=tinyint(0 or 1), amount=decimal(12,2) */
/* ... */
/* output form/table */
echo "<form id='myform' name='myform' >" ;
echo "<table id='mytable' name='mytable'>" ;
while($row = mysql_fetch_array($result))
{
$id = $row['id'] ;
$amount = $row['amount'] ;
$tr_id = "tr_id_" . trim((string)$id) ;
$td_id = "td_id_" . trim((string)$id) ;
$td_amount_id = "td_amount_id_" . trim((string)$id) ;
$input_amount_id = "input_amount_id_" . trim((string)$id) ;
echo "<tr id='$tr_id' name='$tr_id'>";
echo "<td id='$td_id_account' > $id </td>" ;
echo "<td id='$td_amount_id' > <input type='text' id='$input_amount_id' value=$amount > $amount </td>" ;
echo "</tr>";
}
echo "</table>";
echo "</form>" ;
/* submit button and onclick call */
echo "<br />" ;
echo "<table>";
echo "<tr>" ;
echo "<td>";
echo "<button type='button' " . 'onclick="SubmitTableData(\'' . "mytable" .'\');"' . ">Submit</button>" ;
echo "</td>" ;
echo "</tr>";
echo "</table>";
?>
And here is a sample of my JavaScript function used to loop through the rows of the HTML table:
function SubmitTableData(TableID)
{
var table = document.getElementById(TableID);
for (var i = 0, row; row = table.rows[i]; i++)
{
// iterate through rows
for (var j = 0, col; col = row.cells[j]; j++)
{
// iterate through columns
alert(col.innerHTML);
}
/* call PHP procedure with row's cell values as parameters */
/* ... */
break;
}
}
Use the innerText property for the td. Here's a fiddle that shows how to use it.
HTML
<table>
<tr>
<td id="1">Bla</td>
<td id="2"><input id="txt" />Ble</td>
</tr>
</table>​
JavaScript
var td = document.getElementById('1');
alert(td.innerText);
var td2 = document.getElementById('2');
alert(td2.innerText);​
How to grab cell values from a table?
Update to address Elliots comment
See how to grab the cell value (innerText and data-value) in my new demo
In the table the attribute data-value is used to store some data (2B, 3C,..).
<table id="t2">
<thead>
<tr id="tr1"><th>Student Name<th>Course</tr>
</thead>
<tbody>
<tr id="tr2"><td data-value="2B">Bert2 <td>Economics </tr>
<tr id="tr3"><td data-value="3C">Clyde3 <td>Chemics </tr>
<tr id="tr4"><td data-value="4D"> <td>Digital Art</tr>
<tr id="tr5"><td data-value="5E">Ernest <td>Ecmoplasma </tr>
</tbody>
</table>
With jQuery and the right selector you can iterate over each cell:
function eachCell(){
var cellInnerText = [];
var cellValue = [];
var out = document.getElementById("out");
var out2 = document.getElementById("out2");
// iterate over each row in table with id t2 in the table-body (tbody)
$('#t2 tbody tr').each(function(index){
// copy the text into an array
cellInnerText.push($(":first-child", $(this)).text());
//copy the data-value into an array
cellValue.push($(":first-child", $(this)).attr('data-value'));
});
// show content of both arrays
out.innerHTML = cellInnerText.join(" | ");
out2.innerHTML = cellValue.join(" | ");
}
Alert the innerHTML of the first cell in the table's first row
<!DOCTYPE html>
<html>
<head>
<style>
table, td {
border: 1px solid black;
}
</style>
</head>
<body>
<p>Click the button to alert the innerHTML of the first cell (td element with index 0) in the table's first row.</p>
<table id="myTable">
<tr>
<td>Row1 cell1</td>
<td>Row1 cell2</td>
</tr>
<tr>
<td>Row2 cell1</td>
<td>Row2 cell2</td>
</tr>
<tr>
<td>Row3 cell1</td>
<td>Row3 cell2</td>
</tr>
</table>
<br>
<button onclick="myFunction()">Try it</button>
<script>
function myFunction() {
alert(document.getElementById("myTable").rows[0].cells[0].innerHTML);
}
</script>
</body>
</html>
Place IDs on Your inputs with some pattern. for example <input type="text" id="input_0_0" name="whatever" /> where 0 is row and second 0 is column and then instead your alert type
v = document.getElementById('input_'+row+'_'+col).value;
It should help You get rolling now

Categories