JavaScript Create Table and filling with an array content - javascript

I need to create a table in JS which have 3 cells in the first row and in the rest (20 rows) 4 column.
How should I do it work properly if I want to fill the rows from an array value?
So I have myArray[0, 1, 2, 3...] and those values need to insert into the table starting with the second row. (First is like header row)
const apptid_divs11 = [...document.querySelectorAll('.apptSearchResultSelected')];
const apptid_set11 = new Set(apptid_divs11.map(div => div.textContent.trim().split('#')[0]))
The apptid_set11 values needs to go to the table, but the size of the array is always changing

Your question isn't detailed. The following is an example which you can use as a home base
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
<style></style>
</head>
<body>
<table border="1" cellspacing="0">
<thead>
<th>H1</th>
<th>H2</th>
<th colspan="2">H3</th>
</thead>
<tbody></tbody>
</table>
<script>
let myArrayData = Array.from(Array(20), (x, i) => i);
let rows = "";
for (let rowData of myArrayData) {
rows += `
<tr>
<td>${rowData}</td>
<td>${rowData}</td>
<td>${rowData}</td>
<td>${rowData}</td>
</tr>
`;
}
document.querySelector("table tbody").innerHTML = rows;
</script>
</body>
</html>

Related

How to I get a specific part of an element when clicking anywhere in that element with Vanilla Javascript (NO JQuery)?

I want to get from the following html "only" the number 0 or the number 1 depending on which table row I click (FYI: there will be many rows with different numbers):
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<script src="../static/js/test.js"></script>
<title>Document</title>
</head>
<body>
<table>
<tbody id="toAppend">
<tr class="newEle" onclick="setUnstakeNumber()">
<th>
"Stake No"
<div class="d-inline-block"></div>
</th>
<td class="p3 unstakeIdx">0</td>
<td class="p3">Joo: 1</td>
<td class="p3">9/22/2022, 5:02:30</td>
</tr>
<tr class="newEle" onclick="setUnstakeNumber()">
<th>
"Stake No"
<div class="d-inline-block"></div>
</th>
<td class="p3 unstakeIdx">1</td>
<td class="p3">Joo: 2</td>
<td class="p3">9/22/2022, 5:04:18</td>
</tr>
</tbody>
</table>
</body>
</html>
This is how it looks visually:
This is how the html looks in console view:
This is my javascript function:
function setUnstakeNumber() {
let selection = document.getSelection();
let finalSelection = selection.anchorNode.data
let activeTextarea = document.activeElement;
let parent = document.documentElement.parentElement; // Returns the <html> element
console.log(selection);
console.log(finalSelection);
console.log(parent);
console.log(activeTextarea);
}
But none of the above works.
The closest one is the finalSelection, but I need to really click exactly on top of the number I want rather then anywhere in its row.
How do I get the number by clicking anywhere in its element?
So If I would click anywhere in the first row I would get the number 0 and if I would click anywhere in the second row I would get the number 1 with only Vanilla Javascript (No JQuery)?
Try this!
function setUnstakeNumber() {
let selection = document.getSelection();
// get selected row
let selectedRow = selection.anchorNode.parentNode.parentNode;
let index = selectedRow.childNodes[3].innerText;
console.log(index);
}
<html>
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<script src="../static/js/test.js"></script>
<title>Document</title>
</head>
<body>
<table>
<tbody id="toAppend">
<tr class="newEle" onclick="setUnstakeNumber()">
<th>
"Stake No"
<div class="d-inline-block"></div>
</th>
<td class="p3 unstakeIdx">0</td>
<td class="p3">Joo: 1</td>
<td class="p3">9/22/2022, 5:02:30</td>
</tr>
<tr class="newEle" onclick="setUnstakeNumber()">
<th>
"Stake No"
<div class="d-inline-block"></div>
</th>
<td class="p3 unstakeIdx">1</td>
<td class="p3">Joo: 2</td>
<td class="p3">9/22/2022, 5:04:18</td>
</tr>
</tbody>
</table>
</body>
</html>
First get the selected row and then select the which includes the index.

Get data from a table html with click

Good afternoon, I'm a beginner, I'm having trouble getting information from a table that consumes data from an api.
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="style.css">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
<script src="main.js"></script>
<title>Document</title>
</head>
<body onload="apendeOnClick()">
<table id="tablerow">
<caption>Alien football stars</caption>
<thead>
<tr>
<th>DATA</th>
<th>TELEFONE</th>
<th>RAMAL</th>
<th>DESCRIÇÃO</th>
<th>ACÕES</th>
</tr>
</thead>
<tbody id="table_body">
</tbody>
</table>
<script>
</script>
</body>
</html>
My code is this, it feeds the table normally, but I would like when the person clicks on the row button to display the information in the alert.
main.js
fetch("https://my-json-server.typicode.com/lfnoleto/api-fake/contact").then((data) => {
return data.json()
}).then((Objectdata) => {
//console.log(Objectdata[0].data)
let tabelaData = ""
Objectdata.map((values)=>{
tabelaData += `<tr>
<td>${values.data}</td>
<td>${values.tefone}</td>
<td>${values.ramal}</td>
<td>${values.descricao}</td>
<td><button id="butao" class="btn btn-success" ><i class="fa fa-phone"></button></td>
</tr>`
})
document.getElementById("table_body").innerHTML = tabelaData
innerHTML = tabelaData
})
function apendeOnClick(){
const table = document.getElementById("tablerow")
console.log(table)
if (table) {
for (var i = 0; i < table.rows.length; i++) {
table.rows[i].childNodes[5].childNodes[1].onclick = function() {
tableText(this);
};
}
}
}
function tableText(tableRow) {
let telefone = tableRow.childNodes[1].innerHTML;
let ramal = tableRow.childNodes[2].innerHTML;
let obj = {'telefone': telefone, 'ramal': ramal};
console.log(obj);
}
I hope that when the person clicks on the telephone icon, he displays the extension and telephone information
you can use data attribute to store extension info or other information.
<button id="butao" data-extension="123" class="btn btn-success" >
in javascript :
const button = document.querySelector('button');
button.dataset.extention // "123"
a good references:
https://www.w3schools.com/tags/att_data-.asp
https://developer.mozilla.org/en-US/docs/Learn/HTML/Howto/Use_data_attributes

Using checkboxes to render selected items to <div>

I have a populated table of JSON data with a checkbox next to each---I want it so that when a checkbox is selected it pushes that selected item into an array (in this case the div myFave.hs-gc-header).
When I console.log(arr) it just shows a bunch of empty arrays (I believe one for each of the list items). Not sure why this is--if anyone could shed light on this that would be great.
I think the problem lies with the populateArr() block, but I can't say for sure.
JS:
loadTableData() {
let tableRes = redactedName.d.results.filter(function(val) {
return (val.FileLeafRef.trim().length > 0);
}).map(function(obj) {
return {
// "FileName": obj.FileLeafRef,
// "Path": obj.EncodedAbsUrl,
"Titles": obj.File.Name
}
});
let allTitles = tableRes;
for (var i = 0; i < allTitles.length; i++) {
let tr = $("<tr/>");
$(tr).append("<td> </td>");
$(tr).append("<td>" + allTitles[i].Titles + "</td>");
$(tr).append("<input type='checkbox'/>").addClass("checkbox").val("val");
/* ---------- */
function populateArr() {
let arr = [];
$(".checkbox input[type='checkbox']:checked").each(function() {
arr.push($(this).val());
});
return arr;
}
$("#myFave.hs-gc-header").click(function() {
populateArr();
})
};
HTML snippet
<!DOCTYPE html>
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<meta name="viewport" content="width=device-width,initial-scale=1, shrink-to-fit=no">
<meta name="description" content="description here">
<meta name="keywords" content="keywords,here">
<!------------------------------->
<script
src="https://cdnjs.cloudflare.com/ajax/libs/core-js/2.6.2/core.min.js"></script>
<script
type="text/javascript"
src="dist/js/jquery_wrapper.min.js"></script>
</head>
<body>
<script src="./bundle.js"></script>
<div class="km-div-container">
<div class="col-md-2"> <!-- Left -->
<div class="form-group">
<input
type="search"
class="form-control"
id="searchbar"
placeholder="Search All Documents...">
</div>
<div id="myFave.hs-gc-header">
<p>My Favorites:</p>
</div>
</div>
</div> <!-- km -->
</body>
</html>
I don't think this will work, I had a similar problem while using vanilla JavaScript.
When you append to the dom like below, you won't be able to add event listeners to the html tags.
$(tr).append("<input type='checkbox'/>").addClass("checkbox").val("val");
You should do this in your for loop when you filter for the .checkbox with attribute check it should work.
// convert code to jquery
let checkbox = document.createElement('checkbox');
check.setAttribute('type', 'checkbox');
checkbox.className = 'checkbox';
tr.appendChild(checkbox);

jQuery $.each iterating through firebase array twice

I am trying to use jQuery with firebase on the web and am building a quick table of users and tickets. The users and tickets are displaying properly, however they are iterated over twice, in that the table contains the same users and tickets twice. I am not sure what is happening.`
var users = ["Nick","Peter"];
var rows = "";
var number = 0;
//Sync all changes
dbRefAllUsers.on('value', function(snap) {
console.log("#Run",number+1);
jQuery.each(users, function(index,name){
console.log(name);
rows += "<tr><td>" + name + "</td><td>" + snap.child(name).child("tickets").val() + "</td></tr>";
console.log(rows);
});
$(rows).appendTo("#ticketTable tbody");
return head.innerText = JSON.stringify(snap.val(), null, 3);
});`
HTML:
<!DOCTYPE html>
<html>
<head>
<meta content="text/html; charset=UTF-8" http-equiv="content-type">
<title></title>
</head>
<body>
<h1 id="head"></h1>
<script src="https://www.gstatic.com/firebasejs/3.6.7/firebase.js"></script>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.7.1.min.js"></script>
<script src="./app.js"></script>
<table id="ticketTable" style="font-size:18px;">
<thread>
<tr>
<th>Users</th>
<th>Tickets</th>
</tr>
</thread>
<tbody>
</tbody>
</table>
</body>
</html>

how can I select dom with text=? in table?

there is a table:
<html>
<head>
<meta charset="utf-8">
<title>JS Bin</title>
</head>
<body>
<table>
<tr>
<td>dany</td>
<td>lucy</td>
<td>bob</td>
<td>apple</td>
</tr>
</table>
</body>
</html>
now I want select <td>lucy<td> and I want to select it with text
the td with text=lucy
how can I select it with js or jquery ?
If you wanna find a td that contains lucy
Try like this
var td = $("td:contains('lucy')");
If you wanna find a td that have exact text of lucy
Try like this
var td= $("td").filter(function() {
return $(this).text() == "lucy";
})
The following will select all td elements that has 'lucy' as their text.
$("table td").filter(function(){ return $(this).text() == "lucy" });
Try utilizing Array.prototype.filter() , document.querySelectorAll() , Node.textContent , strict equality operator
var td = [].filter.call(document.querySelectorAll("td"), function(el) {
return el.textContent === "lucy"
});
td[0].style.background = "olive";
<html>
<head>
<meta charset="utf-8">
<title>JS Bin</title>
</head>
<body>
<table>
<tr>
<td>dany</td>
<td>lucy</td>
<td>bob</td>
<td>apple</td>
</tr>
</table>
</body>
</html>

Categories

Resources