javascript function only working for first row in table - javascript

I have set up a simple php site where you can filter through a table. At the end of each entry there is a link called "Details" which redirects the user to a site that displays the details of each entry. I want to change the link depending on the filter value the user inputs.
Here is the javascript:
function filterRows() {
var input, filter, table, tr, td, cell, i, j, detailLink;
input = document.getElementById("filterfeld");
filter = input.value.toUpperCase();
table = document.getElementById("ftable");
tr = table.getElementsByTagName("tr");
for (i = 1; i < tr.length; i++) {
tr[i].style.display = "none";
td = tr[i].getElementsByTagName("td");
for (var j = 0; j < td.length; j++) {
cell = tr[i].getElementsByTagName("td")[j];
if (cell) {
if (cell.innerHTML.toUpperCase().indexOf(filter) > -1) {
tr[i].style.display = "";
detailLink = cell.innerHTML;
if(detailLink.indexOf("href=") && document.getElementById("details").getAttribute('href') != "http://google.at"){
var el = document.querySelector('.details');
console.log(el.getAttribute('href'));
el.setAttribute('href',"http://google.at");
console.log(el.getAttribute('href'));
}
break;
}
}
}
}
}
html table:
if ($result->num_rows > 0) {
echo "<table align='center' id='ftable' class='ftable'><tr><th>ID</th><th>Name</th><<th>E-Mail</th><th>Telefon</th><th>Geburtsdatum</th><th>Straße</th><th>Details</th></tr>";
// output data of each row
while ($row = $result->fetch_assoc()) {
echo "<td></td><tr><td>" . $row["id"] . "</td><td>" . $row["firstname"] ." ". $row["lastname"] . "</td><td>" . $row["email"] . "</td>
<td>" . $row["phone"] . "</td><td>" . $row["birthdate"] . "</td><td>" . $row["street"] . "</td>
<td><a href='singleentry.php?id=" .$row["id"]."' class='details' id='details'>Details</a></td></tr>";
}
echo "</table>";
} else {
echo "0 results";
}
I have filled in the example link google.at.
Normally it should change all the links I have in my current table ftable.
The problem is it changes only the first link in the table and then stops.
Appreciate any help!

Related

Export filtered HTML table data to excel using PHPSpreadSheet [duplicate]

I've been working on a function in a PHP system where I can filter the records and then export it to Excel that has a template using PHPSpreadSheet. My problem is that I don't know how to retrieve the filtered records as said in the title above. I think I'm missing something here in my code. This is my code in fetching the records from database into table.
<?php
$conn = mysqli_connect("localhost", "root", "", "db_ims");
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
$sql = "SELECT * FROM tbl_par";
$result = mysqli_query($conn, $sql);
echo "<table id='myTable'>";
echo "<thead><tr><th>Article</th>
<th>Description</th>
<th>Property Number</th>
</tr></thead>";
echo "<tbody>";
while ($row = mysqli_fetch_assoc($result)) {
echo "<tr>";
echo "<td>" . $row['article'] . "</td>";
echo "<td>" . $row['description'] . "</td>";
echo "<td>" . $row['propertyNumber'] . "</td>";
echo "</tr>";
}
echo "</tbody>";
echo "</table>";
// Close the database connection
mysqli_close($conn);
?>
<form action="" method="POST">
<input type="text" id="myInput" onkeyup="filterTable()" placeholder="Search...">
<input type="submit" id="generate" name="generate" value="Submit">
</form>
This is my code in filtering the records:
<script>
function filterTable() {
// Declare variables
var input, filter, table, tr, td, i, txtValue;
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");
for (var j = 0; j < td.length; j++) {
txtValue = td[j].textContent || td[j].innerText;
if (txtValue.toUpperCase().indexOf(filter) > -1) {
tr[i].style.display = "";
break;
} else {
tr[i].style.display = "none";
}
}
}
}
</script>
Lastly, this is the code in exporting the filtered table into excel using PHPSpreadSheet:
<?php
require 'vendor/autoload.php';
use PhpOffice\PhpSpreadsheet\IOFactory;
use PhpOffice\PhpSpreadsheet\Spreadsheet;
if (isset($_POST['generate'])) {
$spreadsheet = IOFactory::load('Template.xls');
//This is the part where I don't know what to put.
$data = array();
$worksheet = $spreadsheet->getActiveSheet();
$row = 10; // Start inserting data from row 10
foreach ($data as $item) {
$worksheet->setCellValue('A'.$row, $item['article']);
$worksheet->setCellValue('B'.$row, $item['description']);
$worksheet->setCellValue('C'.$row, $item['propertyNumber']);
// ...
$row++;
}
$writer = IOFactory::createWriter($spreadsheet, 'Xlsx');
$writer->save('exported_file.xlsx');
}
?>
I tried every possible way that I know but still didn't got my expected result.
If you want to submit the values you need to echo the table inside the form and have something to submit - a hidden field for example - then you can add disabled to the fields you do not want to submit
const hide = txtValue.toUpperCase().indexOf(filter) === -1 : true : false;
tr[i].style.display = hide ? "none" : "";
tr[i].querySelector("[type=hidden]").disabled = hide;
I strongly suggest you use AJAX here instead.

GAS dynamically HTML table created with radiobutton in each row, trying to assign an id to each radiobutton in each row by using a variable name

I have a GAS google apps script web app that has a search box and a button, when clicked, it dynamically loads an HTML table using the input of the user from the previous searchbox, and looks up some data from a google spreadsheet and returns an html table with 3 to 5 rows. the table is created correctly,the first column has only radiobuttons, the second third and 4th has other fields about each user. all of the radiobuttons have the same name i.e. "choiceSelectionRadio", thus they are grouped and only one of them can be selected at once. however, for the next step (posting the information back to the spreadsheet) i need to succesfully identify which radiobutton, and accordingly, which row has the user selected, and for identifying the radiobuttons i need to assign them an id. I tried to name their id by using the count variable in the FOR LOOP, but it is not working. no errors from the console but no assignment so far.
Here is the function i have.
function crearTabla(arrayDatos) {
//si el array de datos es diferente a indefinido y su longitud es diferente a cero
if(arrayDatos && arrayDatos !== undefined && arrayDatos.length != 0){
var tablaResultados = "<table class='table table-sm table-striped' id='dtable' style='font-size:0.8em'>"+
"<thead style='white-space: nowrap'>"+
"<tr>"+
"<th scope='col'>LOTE</th>"+
"<th scope='col'>OP PI</th>"+
"<th scope='col'>CODIGO PI</th>"+
"<th scope='col'>NOMBRE PROD INTERM</th>"+
"<th scope='col'>CANTIDAD (LX)</th>"+
"<th scope='col'>CONVERSION</th>"+
"<th scope='col'>FECHA USAR EN PLANTA</th>"+
"<th scope='col'>CODIGO PT</th>"+
"<th scope='col'>DESCRIPCION</th>"+
"<th scope='col'>SELECCIONADO?</th>"+
"</tr>"+
"</thead>";
//FIRST LOOP: create as many rows as the filtered range in the sheet has
for(var fila=0; fila<arrayDatos.length; fila=fila+1) {
tablaResultados = tablaResultados + "<tr>";
//SECOND LOOP: in each row created, populate with the information filtered
for(var col=0; col<arrayDatos[fila].length+1; col=col+1){
//NOTE: using lenght+1 since i want a final column for placing the radiobuttons
//tablaResultados = tablaResultados + "<td>"+arrayDatos[fila][col]+"</td>";//do loop en each array value
if (col==arrayDatos[fila].length){tablaResultados = tablaResultados + "<td>"+"<input type='radio' name='chooseLote' id='fila'>"+"</td>"} //HERE IS THE PROBLEM************************************************************************
else{
tablaResultados = tablaResultados + "<td>"+arrayDatos[fila][col]+"</td>";//do loop en each array value
}
}
tablaResultados = tablaResultados + "</tr>";
}
tablaResultados = tablaResultados + "</table>";
var div = document.getElementById('espacioParaTablaResultados');
div.innerHTML = tablaResultados;
}else{
var div = document.getElementById('espacioParaTablaResultados');
//div.empty()
div.innerHTML = "No se encontraron coincidencias";
}
}
I prefer to use DOM. This is how I would do it. The reason I prefer DOM is because to achieve this with writing html would require concatination of strings to get the complete html tag. And its easier to add attributes to an html element.
First I would include the table with header in the body of the html page with an id. In this case "myTable".
Then I would get the data from the spreadsheet getData() or this could be done through templated html.
Then I create a radio button in the first column. I assign a value equal to the row it is on.
Then I have a "Submit" button to identify which of the radio buttons has been selected.
My spreadsheet looks like this.
<!DOCTYPE html>
<html>
<head>
<base target="_top">
</head>
<body>
<table id="myTable">
<input id="selectButton" type="button" value="Select" onclick="selectOnClick()">
<tr>
<th>Button</th>
<th>Id</th>
<th>Name</th>
<th>Date</th>
</tr>
</table>
<script>
function selectOnClick() {
let table = document.getElementById("myTable");
for( let i=1; i<table.rows.length; i++ ) { // skip header row
let row = table.rows[i];
let cell = row.cells[0];
if( cell.firstChild.checked ) {
alert(cell.firstChild.value);
return;
}
}
}
function createRow(i,data) {
let table = document.getElementById("myTable");
let row = document.createElement("tr");
let cell = document.createElement("td");
let button = document.createElement("input");
button.setAttribute("type", "radio");
button.setAttribute("name", "radioGroup");
button.setAttribute("value",i+1);
cell.appendChild(button);
row.appendChild(cell);
data.forEach( value => {
let text = document.createTextNode(value);
cell = document.createElement("td");
cell.appendChild(text);
row.appendChild(cell);
}
)
table.appendChild(row);
}
(function() {
google.script.run.withSuccessHandler(
function (data) {
for( let i=0; i<data.length; i++ ) {
createRow(i+1,data[i]);
}
}
).getData();
})();
</script>
</body>
</html>
When the page is displayed it looks like this. And if I select a radio button and press the select button a dialog is displayed.
Perhaps this will work for you:
function crearTabla(datA) {
if (datA && datA !== undefined && datA.length !== 0) {
var tblres = "<table class='table table-sm table-striped' id='dtable' style='font-size:0.8em'>" +
"<thead style='white-space: nowrap'>" +
"<tr>" +
"<th scope='col'>LOTE</th>" +
"<th scope='col'>OP PI</th>" +
"<th scope='col'>CODIGO PI</th>" +
"<th scope='col'>NOMBRE PROD INTERM</th>" +
"<th scope='col'>CANTIDAD (LX)</th>" +
"<th scope='col'>CONVERSION</th>" +
"<th scope='col'>FECHA USAR EN PLANTA</th>" +
"<th scope='col'>CODIGO PT</th>" +
"<th scope='col'>DESCRIPCION</th>" +
"<th scope='col'>SELECCIONADO?</th>" +
"</tr>" +
"</thead>";
for (var i = 0; i < datA.length; i++) {
tblres = tblres + "<tr>";
for (var j = 0; j < datA[i].length + 1; j++) {
tblres = tblres + "<td>" + datA[i][j] + "</td>";
}
tblres = tblres + "<td>" + "<input type='radio' name='chooseLote' id='fila'>" + "</td>"
}
tblres = tblres + "</tr>";
}
tblres = tblres + "</table>";
//I lost track of what was going on down here. I hate everything
not being in English sorry.
}

How to create a table in JS

I need to create a table in JS and show it in the page but it does not seem to work. I have two functions, the first one to actually create the table and the second one to order the elements in the table. I tried creating a simple div in html with id showlist but the table does not appear in the page. Please see the code below.
function myfunction() {
var array2 = [];
var list = "<table border ='1'>";
array2.sort(order);
list = list + "<tr>";
list = list + "<td colspan = '2'> TABLE </td>";
list = list + "</tr>";
list = list + "<tr>";
list = list + "<td> PRICE</td>";
list = list + "</tr>";
for (i = 0; i <= array2.length; i++) {
list = list + "<tr>";
list = list + "<td>" + array2[i].name + "</td>";
list = list + "<td>" + array2[i].price + "</td>";
list = list + "</tr>";
}
list = list + "</table>";
$("#showlist").html(list);
}
function order(n1, n2) {
if (n1.price > n2.price) {
return 1;
} else {
if (n1.price < n2.price) {
return -1;
} else {
return 0;
}
}
}
Your for loop <= runs from 0 to array2.length, it should be < - from 0 to array2.length-1.
for (i = 0; i < array2.length; i++) {
// ^_ Notice change here
...
}
Else, the last iteration would throw undefined errors.
Uncaught TypeError: Cannot read property 'name' of undefined
Fiddle Example

How to re-order table row numbers when rows are added and removed

I am dynamically generating table rows using javascript (no jquery involved). Each row has 3 cells zone number, input, and a delete button. The number of rows added uses a select box to if they select 3, 3 rows are added ect. What I want to happen is if they add 3 rows then add another 3. the rows will be will displayed as 1,2,3,4,5,6, Currently its 1,2,3,1,2,3. I also what to re-order the rows when a row is deleted.
Current code php file:
function display_Zones($focus, $field, $value, $view){
global $locale, $app_list_strings, $mod_strings;
$html = '';
if($view == 'EditView'){
$html .= '<script src="modules/dry_Zones/zone_items.js"></script>';
$html .= "<div style='padding-top: 10px; padding-bottom:10px;'>";
$html .= "<select id='zone' name='zone'>";
$html .= get_select_options_with_id($app_list_strings["zone_list"]);
$html .= "</select> ";
$html .= "<input type=\"button\" tabindex=\"116\" class=\"button\" value=\"addZone\" id=\"addZone\" onclick=\"insertZone()\" />";
$html .= "</div>";
$html .= "<table border='0' cellspacing='4' width='40%' id='zoneItems'>";
$html .= "<tr><td></td><td>Motor Reference Point</td><td></td></tr>";
$html .= "</table>";
return $html;
}
javascript file:
var num = 1;
function insertZone() {
var table = document.getElementById('zoneItems');
var e = document.getElementById('zone');
var number = e.options[e.selectedIndex].value;
if(number != ''){
for (var i=0; i < number; i++)
{
var x = table.insertRow(-1);
var a = x.insertCell(0);
num = num+i;
a.innerHTML = "<span>Zone: "+num+"</span> ";
var b = x.insertCell(1);
b.innerHTML = "<input type='text' name='motor_ref_point' size='18' value='' />";
var c = x.insertCell(2);
c.innerHTML = "<button class='button lastChild' onclick='removeZone(this)' ><img src='themes/default/images/id-ff-clear.png'></button>";
}
}
}
function removeZone(rows) {
var _row = rows.parentElement.parentElement;
document.getElementById('zoneItems').deleteRow(_row.rowIndex);
}
Probably not the most efficient, way, but I don't think you'll notice any problems unless you have thousands of rows. When you add/delete rows, you could just iterate through the first table cell of each row and update it based on the index.
Array.prototype.forEach.call(document.querySelectorAll('td:first-child'),
function (elem, idx) {
elem.innerHTML = idx + 1;
});
http://jsfiddle.net/ExplosionPIlls/2QxX6/
Ended up just doing it like this:
function insertZone() {
var table = document.getElementById('zoneItems');
var e = document.getElementById('zone');
var number = e.options[e.selectedIndex].value;
if(number != ''){
for (var i=0; i < number; i++)
{
var x = table.insertRow(-1);
var a = x.insertCell(0);
num = i+1;
// a.innerHTML = "<span>Zone: "+num+"</span> ";
var b = x.insertCell(1);
b.innerHTML = "<input type='text' name='motor_ref_point' size='18' value='' />";
var c = x.insertCell(2);
c.innerHTML = "<button class='button lastChild' onclick='removeZone(this)' ><img src='themes/default/images/id-ff-clear.png'></button>";
}
count();
}
}
function removeZone(rows) {
var _row = rows.parentElement.parentElement;
document.getElementById('zoneItems').deleteRow(_row.rowIndex);
count();
}
function count(){
var table = document.getElementById("zoneItems");
var tbody = table.tBodies[0];
row_count = tbody.rows.length - 1;
for (var i = 0, row; row = tbody.rows[i]; i++) {
if(i != 0){
for (var j = 0, col; col = row.cells[j]; j++) {
if(j == 0){
col.innerHTML = "<span>Zone: "+i+"</span> ";
}
}
}
}
}

get id of a cell in a table inside a div (JS and HTML)

Hi I have a php script that draws a table subject to certain conditions. When the table is drawn it is inside a div called ‘window’ and the table is called ‘visi’ I then want to use the code below to get the id’s of each cell in the table. I can get the class name no problem but get absolutely nothing from the id. Can anyone give me an idea of what i am doing wrong?. I have tried a similar peice of code on a table that is not inside a div and it works fine. Any help would be great and I hope the code makes sense.
function confirm_allocate() {
var msg = ""
var tab = document.getElementById('visi');
var r = tab.rows.length
for (i=0; i<r; i++){
cc = tab.rows.cells.length
for (col=0; col<cc; col++){
x=document.getElementById('visi').rows.cells;
iden = x[col].className
ref = x[col].id
msg += "Class =" + iden + " /// Id =" + ref + "\r"
}
}
alert (msg )
}
If it helps this is the code to draw the table (but this is called using js/ ajax after getting the information for the table )
<?php
$table = "" ;
include '../database_sql/dbconnect.php' ;
include '../functions/job_details.php';
include '../functions/check_date.php';
include '../functions/stock_list.php' ;
include '../functions/allocated_on_date.php' ;
$jobdate = $_GET['jobdate'] ;
$jobnumber = $_GET['jobnumber'] ;
$jobname = $_GET['jobname'] ;
$screens = screens_per_job($jobnumber,$size) ;
$table = "<h2 align= 'center' > $jobname (Job Number $jobnumber) : Screens required : $screens </h2>" ;
$table .= "<table id='visi' width='480px' align='center' cellspacing='1' cellpadding='1' border='1' ><tr>" ;
// get stock list from DB
stock_list() ;
$len = count( $stock);
$evresult = mysql_query("SELECT * FROM event WHERE jobnumber = '$jobnumber' ") ;
$event_row = mysql_fetch_array($evresult);
for ($counter = 0; $counter < $len; $counter++) {
$item = $stock[$counter] ;
$items = $item . "s" ;
$booked_for_job = $event_row[$items] ;
$result = mysql_query("SELECT * FROM $item ") ;
allocated_on_date($jobdate) ; // function
if ($booked_for_job) {
$count = 1 ;
$table .= "<td >$item<br> [$booked_for_job to Allocate] </td> " ;
WHILE ($row = mysql_fetch_array($result)) { ;
$booked_job = $screens[$item][$count]["job"] ; // from the allocated_on_date($jobdate) function
$description = $row['trailer_id'];
$class = $items ;
$id_items = $items . $count ;
$count ++ ;
if ($booked_job == $jobnumber) { // allocated to current job
$table .= "<td class='truckbox' > <div class='$class' id='$id_items' onClick='allocate(\"$booked_for_job\",\"$id_items\")' > " ;
$table .= "$num </div> </td>" ;
} ELSEIF ($booked_job === 0 ) { // available to allocated
$class .= "g" ;
$table .= "<td class='truckbox' > <div class='$class' id='$id_items' onClick='allocate(\"$booked_for_job\",\"$id_items\")' > " ;
$table .= "$num </div> </td>" ;
} ELSE { // allocated to ANOTHER job
$class .= "a" ;
$table .= "<td class='truckbox' > <div class='$class' id='$items' > " ;
$table .= "</td> " ;
}
} // while
$table .= "</tr>" ;
} ; // if
}; //for
$table .= "</table> " ;
$table .= "<table width='200px' align='center' cellspacing='12' cellpadding='1' ><tr>" ; // draw table buttons close and allocate
$table .= "</tr><tr>" ;
$table .= "<td class='truckbox' <div class='yesbutton' id='yes' onClick='confirm_allocate()' ; return false ; > ";
$table .= "<td class='truckbox' <div class='nobutton' id='no' onClick='hide()' > ";
$table .= "</tr></table> ";
echo $table ; // finally draw table
include '../database_sql/dbclose.php' ;
?>
I don't see any id attributes on the table cells (td elements) that are being generated. So ref is just going to be blank or undefined.
If that's not the problem then it could be the .rows.cells. Try .getElementsByTagName('td') instead. I think that line should be outside the loop, since it's not changing on each iteration.
Also, the latter part of your HTML is wrong - you don't close the td tag. Instead of <td class='truckbox' <div class... it should be <td class='truckbox'><div class...
You forgot to access the array elements:
...
for (i=0; i<r; i++) {
var row = tab.rows[i];
var cc = row.cells.length;
for (col=0; col<cc; col++){
var x = row.cells[col];
...

Categories

Resources