Multiple elements using appendChild for table - javascript

I have the following input and button
const inputNotice = document.createElement("input");
inputNotice.type = "text";
r.insertCell(26).appendChild(inputNotice.cloneNode(true));
//new button
const Noticebutton = document.createElement("button");
Noticebutton.type = "button";
Noticebutton.textContent = "Send Notice";
r.insertCell(26).appendChild(Noticebutton);
Im trying to get the input field and button to sit in 1 cell in the table, it creates these in 2 separate cells.

create a div having input and button as children and then append this as the child of the cell like this:
const div= document.createElement('div');
const inputNotice = document.createElement('input');
const Noticebutton = document.createElement("button");
div.appendChild(inputNotice);
div.appendChild(NoticeButton);

Since there is no html template provided, I have had one of my own to do the illustration.
The idea is to add both of the elements inside a container and then append that container to the cell as a child.
In the following illustration I have used a div as a container. Feel free to choose one of which that suits the needs.
Illustration
const nonWorkingRow = document.querySelector('#cell-host-non-working');
const inputNotice = document.createElement("input");
inputNotice.type = "text";
// inputNotice.style.display = 'inline block';
nonWorkingRow.insertCell(0).appendChild(inputNotice.cloneNode(true));
//new button
const Noticebutton = document.createElement("button");
Noticebutton.type = "button";
Noticebutton.textContent = "Send Notice";
// Noticebutton.style.display = 'inline block';
nonWorkingRow.insertCell(0).appendChild(Noticebutton.cloneNode(true));
const workingRow = document.querySelector('#cell-host');
const container = document.createElement('div');
container.appendChild(inputNotice);
container.appendChild(Noticebutton);
workingRow.insertCell(0).appendChild(container);
.column-bordered-table thead td {
border-left: 1px solid #c3c3c3;
border-right: 1px solid #c3c3c3;
}
.column-bordered-table td {
border-left: 1px solid #c3c3c3;
border-right: 1px solid #c3c3c3;
}
.column-bordered-table tfoot tr {
border-top: 1px solid #c3c3c3;
border-bottom: 1px solid #c3c3c3;
}
<h1>Non Working</h1>
<table id="row-host-non-working" class="column-bordered-table">
<tr id="cell-host-non-working" style="outline: thin solid">
<td>
<p>Hello</p>
</td>
</tr>
</table>
<h1>Working</h1>
<table id="row-host-working" class="column-bordered-table">
<tr id="cell-host" style="outline: thin solid">
<td>
<p>Hello</p>
</td>
</tr>
</table>
WYSIWYG => WHAT YOU SHOW IS WHAT YOU GET

Instead of inserting a new cell twice (which is the cause of your problem), do that only once and work with the reference insertCell provides:
const cell = r.insertCell(26);
const inputNotice = document.createElement("input");
inputNotice.type = "text";
const Noticebutton = document.createElement("button");
Noticebutton.type = "button";
Noticebutton.textContent = "Send Notice";
cell.append(inputNotice, Noticebutton);
Notice I'm using append here, not appendChild, because it allows to pass a number of elements to it rather than just one.

Related

How can I use method on object which name I have as a string?

I'm coming back with another problem.
I have such code:
HTML
<button>first</button>
<button>second</button>
<div class="first"></div>
<div class="second"></div>
CSS
div{
margin-top: 10px;
width: 100px;
height: 100px;
border:1px solid black;
background-color: #ddd;
}
JS
const btns = document.querySelectorAll("button");
const first = document.querySelector(".first");
const second = document.querySelector(".second");
btns.forEach(btn => btn.addEventListener("click", function(){
this.classList.toggle("pressed");
let selection = this.textContent;
// selection.style.transform = "translate(100px)";
}))
https://codepen.io/ptr11dev/pen/oREymM
I'd like to create one function that'll be responsible for moving respective div to the right side by 100px - I stuck with such problem. Under "selection" I have respective name of div (stored under the same name), but simple code like
selection.style.transform = "translate(100px);"
doesn't work. I know that workaround like creating two functions and using
first.style.transform = "translate(100px);"
and
second.style.transform = "translate(100px);"
would work, but in my main code it's a bit more complicated.
I'll really appreciate any input from your side. Thanks
P.S. I'd like to use Vanilla JS.
You can find them by the class name, assuming that the button text and their class are the same.
const btns = document.querySelectorAll("button");
const first = document.querySelector(".first");
const second = document.querySelector(".second");
btns.forEach(btn => btn.addEventListener("click", function(){
this.classList.toggle("pressed");
let selection = this.textContent;
document.querySelector(`.${selection}`).style.transform = "translate(100px)";
}))
div{
margin-top: 10px;
width: 100px;
height: 100px;
border:1px solid black;
background-color: #ddd;
}
<button>first</button>
<button>second</button>
<div class="first"></div>
<div class="second"></div>
Your problem is textContext is just that TEXT not an object. This sets selection as the first element that matches the class name pulled as this.textContent;
let selection = document.getElementsByClassName(this.textContent)[0];
selection.style.transform = "translate(100px)";

Make an element and put it into a group of elements

I want to make a div and put it into all elements that have .folio-item class but I don't know how to do that.
You can use a query selector to get all elements with the class of folio-item. You can then use a for loop to iterate through those elements and create a div to append to those elements with document.createElement.
.folio-item{
border: 1px solid blue;
}
<div class="folio-item">
1
</div>
<div class="folio-item">
2
</div>
<div class="folio-item">
3
</div>
<script>
var divs = document.querySelectorAll(".folio-item");
for(let i = 0; i < divs.length; i++){
var div = document.createElement("div");
div.innerHTML = "<b style='color: red;'>Appended div</b>";
div.style.border = "1px solid green";
div.style.padding = "10px";
div.style.margin = "5px";
divs[i].appendChild(div);
}
</script>

Javascript Dynamic Table with each cell having an onmouse event?

I've created a dynamic table using Javascript. Now what I'm trying to do is for each cell that is dynamically generated, there is an onmouseover event that would change that particular cell's backgroundColor.
The problem I have is that when I generate the table and try to have an onmouseover function with each dynamically generated cell the function only works for the last generated cell.
Here's a copy of my code. (Note: I have only tested this on Chrome)
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
<style>
table, th, td {
border: 1px solid black;
border-collapse: collapse;
padding: 5px;
text-align: center;
}
</style>
<script type="text/javascript">
var table;
function init(){
table = document.getElementById("mytable");
}
function makeCells(){
init();
for(var a=0;a<20;a++){
var row = table.insertRow(-1);
for(var b=0;b<20;b++){
cell = row.insertCell(-1);
cell.innerHTML = a*b;
cell.onmouseover = function(){cell.style.backgroundColor = "yellow";};
}
}
}
</script>
</head>
<body onload="javascript: makeCells();">
<table id="mytable"></table>
</body>
</html>
Any advice would be greatly appreciated.
Some Improvements. 3 things I would change:
Don't edit inline styles with javascript. Instead, add or remove a class. see # 3.
Don't do so many event handlers in your "onload", "onmouseover". Its better to add an event listener.
It is better performance to add all of the new elements at one time instead of individually. See this article: https://developers.google.com/speed/articles/reflow
Here is a way to optimize the Javascript:
HTML
<table id="table"></table>
CSS
body {
padding: 40px;
}
.yellow {
background: yellow;
}
td {
padding: 10px 20px;
outline: 1px solid black;
}
JavaScript
function propegateTable() {
var table = document.getElementById("table");
//will append rows to this fragment
var fragment = document.createDocumentFragment();
for(var a=0; a<10; a++){ //rows
//will append cells to this row
var row = document.createElement("tr");
for(var b=0;b<5;b++){ //collumns
var cell = document.createElement("td");
cell.textContent = a + ", " + b;
// event listener
cell.addEventListener("mouseover", turnYellow);
row.appendChild(cell);
}
fragment.appendChild(row);
}
//everything added to table at one time
table.appendChild(fragment);
}
function turnYellow(){
this.classList.add("yellow");
}
propegateTable();
http://codepen.io/ScavaJripter/pen/c3f2484c0268856d3c371c757535d1c3
I actually found the answer myself playing around with my code.
In the line:
cell.onmouseover = function(){cell.style.backgroundColor = "yellow";};
I changed it to:
cell.onmouseover = function(){this.style.backgroundColor = "yellow";};

HTML - read .txt file from URL location in javascript

I want to read a .txt file an URL location, lets say from http://www.puzzlers.org/pub/wordlists/pocket.txt and process its content on my page.
Can you point me out some tutorials or some basic code on how to do this in javascript?
I have a basic HTML code where I have some tables and I want to populate them with text from a .txt from a given URL location, but I do not know how to read the data from that location.
<html>
<head>
<title>Pseudoganglia Interface</title>
<!-- CSS goes in the document HEAD or added to your external stylesheet -->
<style type="text/css">
table.gridtable {
font-family: verdana,arial,sans-serif;
font-size:11px;
color:#333333;
border-width: 1px;
border-color: #666666;
border-collapse: collapse;
}
table.gridtable th {
border-width: 1px;
padding: 8px;
border-style: solid;
border-color: #666666;
background-color: #dedede;
}
table.gridtable td {
border-width: 1px;
padding: 8px;
border-style: solid;
border-color: #666666;
background-color: #ffffff;
}
</style>
<!-- Table goes in the document BODY -->
<script>
function getText()
{
// read text from URL location
}
function populateTables() {
var tableHP = document.getElementById("tHP");
// Create an empty <tr> element and add it to the 1st position of the table:
var row = tableHP.insertRow(tableHP.rows.length);
// Insert new cells (<td> elements) at the 1st and 2nd position of the "new" <tr> element:
var cell1 = row.insertCell(0);
var cell2 = row.insertCell(1);
// Add some text to the new cells:
cell1.innerHTML = "NEW CELL1";
cell2.innerHTML = "NEW CELL2";
}
</script>
</head>
<body onload="populateTables()">
<table class="gridtable" id="tHP">
<tr>
<th colspan=2>HP</th>
</tr>
<tr>
<td># SN</td>
<td>% of used RAM</td>
</tr>
</table>
<br>
<table class="gridtable" id="tIBM">
<tr>
<th colspan=2>IBM</th>
</tr>
<tr>
<td># CN</td>
<td>% of used RAM</td>
</tr>
</table>
</body>
</html>
this code may help you:
function getText(){
// read text from URL location
var request = new XMLHttpRequest();
request.open('GET', 'http://www.puzzlers.org/pub/wordlists/pocket.txt', true);
request.send(null);
request.onreadystatechange = function () {
if (request.readyState === 4 && request.status === 200) {
var type = request.getResponseHeader('Content-Type');
if (type.indexOf("text") !== 1) {
return request.responseText;
}
}
}
}
function populateTables(){
var outer_text = getText();
outer_text = outer_text.split('\n'); // you can adjust the manner of parsing the received file (regexp)
var tableHP = document.getElementById("tHP");
// Create an empty <tr> element and add it to the 1st position of the table:
var row = tableHP.insertRow(tableHP.rows.length);
// Insert new cells (<td> elements) at the 1st and 2nd position of the "new" <tr> element:
var cell1 = row.insertCell(0);
var cell2 = row.insertCell(1);
// Add some text to the new cells:
cell1.innerHTML = outer_text[0];
cell2.innerHTML = outer_text[1];
}
from codegrepper using fetch (unsupported on IE).
const url = "http://www.puzzlers.org/pub/wordlists/pocket.txt"
fetch(url)
.then( r => r.text() )
.then( t => //process your text! )

Hide column while exporting to excel from html table using javascript

I have a html table which I have to export to excel , but while doing so, I dont want some of the td elements to be exported. When I apply javascript to hide the td, the changes are being applied only to the view form and not to the the content being exported.
Need help in how to export in this case.
I have included html, css and script all in one page.
<html>
<body>
<div id="myDiv">
<table id="metrics" border="1px" cellspacing="0 px" style="border-style: solid; border-color: Black;
border-width: thin;">
<tr>
<td style= "background-color: #bfbfbf; font-size: small; color: black;">
LOB
</td>
<td>
<span class="hillbillyForm" data-displayname='LOB' style="display:none;"></span>
</td>
</tr>
</table>
<input type="button" id="btnExport" value="Export" onclick="TableToExcel('metrics');" />
</div>
</body>
Here I want to hide the td which contains span class "hillbillyForm"
The javascript That I am using is
function TableToExcel(tableid) {
var id = $('[id$="' + tableid + '"]');
var $clonedTable = $("id").clone();
$clonedTable.find('[style = "display: none"]').remove();
var strCopy = $('<div></div>').html(id.clone()).html();
window.clipboardData.setData("Text", strCopy);
var objExcel = new ActiveXObject("Excel.Application");
objExcel.visible = false; var objWorkbook = objExcel.Workbooks.Add; var objWorksheet = objWorkbook.Worksheets(1); objWorksheet.Paste; objExcel.visible = true;
}
</script>
So what I'm understanding is that you want to remove all TD's which have a direct child with the class hillbillyForm.
You can do something like this:
var form = document.getElementById(tableid),
exportForm = form.cloneNode(true),
elementsToRemove = exportForm.querySelectorAll('.hillbillyForm');
for (var i = elementsToRemove.length; i--;){
var td = elementsToRemove[i].parentElement;
if (td) td.parentElement.removeChild(td);
}
jsFiddle

Categories