Handling the table from a html form with javascript - javascript

<table id="production">
<tr>
<th>Product Name</th>
<td></td>
<td>elementsdefined</td>
</tr>
<tr>
<th>Product Name</th>
<td></td>
<td>elementsdefined</td>
</tr>
</table>
Product Name:
Product Quanitity:
Add
function updateForm() {
var prdn = document.getElementById("prodname").value;
var prdq = document.getElementById("prodquantity").value;
var table = document.getElementById("production");
var rows = table.rows;
var cell1 = rows[0].insertCell(-1);
var cell2 = rows[1].insertCell(-1);
cell1.innerHTML = prdn;
cell2.innerHTML = prdq;
}
I need someone help me understand how I can insert data in separate column in database; suppose I have a table of three rows and three columns, columns are created by using td tags, now in the first and last columns elements are predefined and so any data should insert in the second column of the table after clicking the button. because the code above is inserting the data in raw cells by default.
i am adding the fiddle here
http://jsfiddle.net/3e7rh/2/

As you can see here, you need to add in the last - 1 column.
http://jsfiddle.net/3e7rh/8/
function updateForm() {
var prdn = document.getElementById("prodname").value;
var prdq = document.getElementById("prodquantity").value;
var table=document.getElementById("production");
var rows=table.rows;
var cell1=rows[0].insertCell(rows[0].cells.length - 1);
var cell2=rows[1].insertCell(rows[1].cells.length - 1);
cell1.innerHTML=prdn;
cell2.innerHTML=prdq;
}
Update:
http://jsfiddle.net/3e7rh/10/
function updateForm() {
var prdn = document.getElementById("prodname").value;
var prdq = document.getElementById("prodquantity").value;
var table=document.getElementById("production");
var rows=table.rows;
var cell1=rows[0].cells[1].textContent=prdn;
var cell2=rows[1].cells[1].textContent=prdq;
}

Get the table. Iterate over all rows and fill in the first td (Because you are using th as the first one)
var table = document.getElementById("production")
rows = table.getElementsByTagName("tr");
for(var i=0;i<rows.length;i++)
{
columns = rows[i].getElementsByTagName("td");
columns[0].textContent="text"; //First Td second column in your case
}
Jsfiddle:http://jsfiddle.net/7xs6v/1/
I am assuming you want to fill the same text in every first td(second column). If you want individual then you can use the index specificallyinstead of iterating over for loop

Related

javascript im trying to append button to the end of each row in my table

so im trying to add a buttons to the end of each row since the table is dynamic I have to use javascript to append it but everytime I try it doesn't work if it does it will just put a button at the end of the last row of the table. Heres an image of what I get linked below
enter image description here
<!--TABLE HEADER SECTION-->
<div class="div0">
<table class="tableHeader">
<thead>
<tr>
<th>Store</th>
<th>Product</th>
<th>Profile</th>
<th>Proxies</th>
<th>Status</th>
<th>ACTION</th>
</tr>
</thead>
</table>
</div>
<!--TABLE SECTION-->
<div class="div1">
<table id = "botTasksTable" class="table table-dark table-sm table-bordered">
<tbody>
<tr>
<td>another name</td>
<td>mockdata</td>
<td>mockdata</td>
<td>mockdata</td>
<td>mockdata</td>
</tr>
</tbody>
</table>
</div>
<script type="text/javascript">
const tableBody = document.querySelector("#botTasksTable > tbody");
//function to load table into tbody from jsonfile bottable which would be the users given tasks
function loadBotTasksTable() {
const request = new XMLHttpRequest();
request.open("get", "data/botTable.json"); //grabs the data from the json file its in the data file/ and named bottable.json
request.onload = () => {
const json = JSON.parse(request.responseText); //attempts to parse the data it gets
populateTable(json);
};
request.send(); //sends out the request for thr function
}
var btn = document.createElement("BUTTON");
var btn = document.createElement("BUTTON"); // Create a <button> element
btn.innerHTML = "CLICK ME"; // Insert text
function populateTable(json) {
//this while loop clears out existing table data!
//we want to add this back but adding a value to first child even if its a mock value.
while (tableBody.firstChild) { //so basically checking if the table has <tr> <td></td> </tr> so a row and column
tableBody.removeChild(tableBody.firstChild)
}
//now we populate table
json.forEach((row) => { //loops through each row [ SUPREME, Nike SB Dunks, profile1, proxy22, In Progress ]
const tr = document.createElement("tr"); //create the new row
row.forEach((cell) => { //loops through each individual column of the row EX : SUPREME
const td = document.createElement("td");
td.textContent = cell // passes whatever data the json file had in the cell into the text content of the row
tr.appendChild(td);
});
//for each cell in the row get the index and append
tableBody.appendChild(tr); //appends the row into the table body row by row as i runs through the for loop
});
loopTable();
}
//loop through table and add button to the table
function loopTable() {
var table = document.getElementById('botTasksTable');
for (var i = 0, row; row = table.rows[i]; i++) {
//iterate through rows
//rows would be accessed using the "row" variable assigned in the for loop
row.appendChild(btn);
console.log(i);
}
};
You need to create a new button for each row, and put it inside a <td>. You can use cloneNode() to make a copy of an element.
//loop through table and add button to the table
function loopTable() {
var table = document.getElementById('botTasksTable');
for (var i = 0, row; row = table.rows[i]; i++) {
let td = document.createElement('td');
td.appendChild(btn.cloneNode());
row.appendChild(td);
console.log(i);
}
};

Create row in html table which does not have id and class

I would like to create one additional row in HTML Table which is very common and can be done if we have id or class available of that table.
But in my case I have one page which contains many forms and tables.
But in all those I have one form which contains only one element i.e table and I would like to create one more row and move few columns from 1st row to newly created row.
For this I have created simple HTML page.Please find below code and help me to achieve my output.
<h:form id="myForm">
<table>
<tr>
<td id="col1">Item Info</td>
<td id="col2">Description</td>
<td id="col3">Product</td>
<td id="col4">Keywords</td>
<td id="col5">Documents</td>
<td id="col6">Image</td>
<td id="col7">Video</td>
</tr>
</table>
</h:form>
Here Ia m getting output like
Item Info Description Product Keywords Documents Image Video
But I want to achieve something like below:
Item Info Description Product Keywords
NEW CELL1 Documents Image Video
means I would like to remove few columns from existing row and I would like to add it in newly created row.
For this I have written Javascript like:
<script type="text/javascript">
window.onload = function() {
split();
};
function split() {
var form = document.getElementById("myForm");
var table = form.elements[0];
var tr = document.createElement("tr");
tr.id="row2";
table.appendChild(tr);
var cell = tr.insertCell(0);
cell.innerHTML = "NEW CELL1";
var col5 = document.getElementById("col5");
tr.appendChild(col5);
var col6 = document.getElementById("col6");
tr.appendChild(col6);
var col7 = document.getElementById("col7");
tr.appendChild(col7);
}
</script>
Here, My problem is this entire form will be generated automatically so I can't give the Id for the table and with this script it is not identifying my table when I am giving form.elemets[0];
I want to find table element so that I can create row in that table.
You can find the table by doing this:
Get one of the elements in a table row, and get the parent node until you've got the table. In this case you could do document.getElementById('col1').parentNode.parentNode
And just to ease things,
You can insert this string '</tr><tr>' in a row, after a table cell, to easily create a new row.
This should be better than document.getElementsByTagName('table'), because if you have lots of tables which are far away, it will take more time to find your table's index in that array.
Use getElementsByTagName to get the table from within your form, which has an ID
window.onload = function() {
split();
};
function split() {
var form = document.getElementById("myForm");
var table = form.getElementsByTagName("table")[0];
var tr = document.createElement("tr");
tr.id = "row2";
table.appendChild(tr);
var cell = tr.insertCell(0);
cell.innerHTML = "NEW CELL1";
/*Your original code produces duplicate IDs which is a BAD thing*/
var col5 = document.getElementById("col5");
/*Update new Id*/
col5.id += "_new";
tr.appendChild(col5);
var col6 = document.getElementById("col6");
/*Update new Id*/
col6.id += "_new";
tr.appendChild(col6);
var col7 = document.getElementById("col7");
/*Update new Id*/
col7.id += "_new";
tr.appendChild(col7);
}
<form id="myForm">
<table>
<tr>
<td id="col1">Item Info</td>
<td id="col2">Description</td>
<td id="col3">Product</td>
<td id="col4">Keywords</td>
<td id="col5">Documents</td>
<td id="col6">Image</td>
<td id="col7">Video</td>
</tr>
</table>
</form>
You also have a mismatch of column numbers, with the code provided you originally have 7 columns and only insert 4, this will produce inconsistent results, make sure to use the colspan attribute as needed.
You should be able to use JavaScript's querySelector method to select the table data you want to remove from the document.
Something like var rowToDeleteOrAddTo = document.querySelector("#myForm > table > tr > td"); should help you get there. You'll need to lookup CSS Selectors to get the specific selectors you need. You may need to use the textContent property once you have a node to make sure you are deleting the right one.

Delete all rows in an HTML table except for header with JS

So I am having trouble deleting all of the data in an HTML table with js WITHOUT deleting the header. Here is my HTML:
<html>
<title>Z80 Opcodes</title>
<body>
<input type="text" id = "input" value = "">
<button onClick = "hex()">Hex</button>
<button onClick = "bin()">Bin</button>
<button onClick = "assem()">Assembly</button>
<button onClick = "find()">Find</button>
<table id = "out" style="width:100%">
<thead>
<th align="left">Binary</th>
<th align="left">Hex</th>
<th align="left">Assembly</th>
<th align="left">Description</th>
</thead>
<tbody id="tb">
</tbody>
<script src = "js/script.js">
</script>
</body>
</html>
And here is script.js:
var id = document.getElementById("out");
var ab = "";
var row;
var table = ['0000000000nopno operation', '0000000101ld (bc), **loads ** into BC'];
var bin = ['00000000', '00000001'];
var hex = ['00', '01'];
var assembly = ['nop', 'ld (bc), **'];
var description = ['no operation', 'loads ** into BC'];
l = table.length;
function find() {
row = id.insertRow(0);
for (i=0;i <=l-1;i++) {
ab = table[i];
if (ab.includes(document.getElementById("input").value)) {
row = id.insertRow(-1);
cell1 = row.insertCell(0);
cell2 = row.insertCell(1);
cell3 = row.insertCell(2);
cell4 = row.insertCell(3);
cell1.innerHTML = bin[i];
cell2.innerHTML = hex[i];
cell3.innerHTML = assembly[i];
cell4.innerHTML = description[i];
}
}
}
I have omitted A LOT of array entries because they contained almost the FULL instruction set of thee z80 microprocessor.
What this code does (basically) is it gets an input from the user and if the array table contains that input then it gets the corresponding values from bin, hex, assembly and description and assigns each a column in the table out, then adds a row with the for the data. However, I cannot seem to find a way to delete all of the rows in tbody before another set of values are appended to the table without deleting thead. I have searched around on the web and found several solutions, none of which worked. They either deleted the thead or caused some kind of error (I'll give examples if you ask). I am using Google Chrome version 63.0.3239.132 web browser to run my code.
As you may be able to see I am quite new to js and HTML
Any ideas what I have done wrong?
~Jachdich
First You have to close your <table> tag </table>
This is how you can clear your table.
$('#remove').on('click', ()=>{
$('#tb').empty()
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table id = "out" style="width:100%">
<thead>
<th align="left">Binary</th>
<th align="left">Hex</th>
<th align="left">Assembly</th>
<th align="left">Description</th>
</thead>
<tbody id="tb">
<tr>
<th>01010101</th>
<th>1231:sdf:sdf42</th>
<th>213123</th>
<th>description</th>
</tr>
</tbody>
</table>
<button id="remove">
clear
</button>
Assuming you want to keep the tbody element intact instead of just removing it and all its children at once:
// get a reference to the tbody element
var tb = document.querySelector('#out tbody');
// while tb has children, remove the first one
while (tb.childNodes.length) {
tb.removeChild(tb.childNodes[0]);
}
// tb is now empty
From a semantic perspective, it would make the removal of rows much easier if you added them to the <tbody> element instead of the <thead> element. This way, you could target the rows within the body and remove them whilst preserving your <thead> (sibling node to ):
var body = document.querySelector('tbody');
while (body.firstChild) {
// This will remove all children within tbody which in your case are <tr> elements
body.removeChild(body.firstChild);
}
body.removeChild(rowsWithinBody)
https://developer.mozilla.org/en-US/docs/Web/HTML/Element/tbody#examples
with jQuery you can do it simply in a single line of code.
$("#table_id tbody tr").remove();
it will remove all rows in a table except the header.

Dynamic table from Firebase using JavaScript for website

I am creating a table using Google Firebase in JavaScript, but its not showing the table.
Here is my code:
User Table <!--function called on click on tab link-->
<table id="userTableInside" class="w3-table w3-centered w3-striped w3-card-2">
<tr style="background: #cccccc;">
<th>Institute Name</th>
<th>Role id</th>
<th>Institute id</th>
<th>Strikes</th>
<th>Status</th>
<!--<th>Perfomance Rating</th>-->
</tr>
<tr id="mytr">
</tr>
</table>
Added the src script tag above
<script>
//initialized firebase also
function tab1() {
var table= document.getElementById("userTableInside");
var i = 1;
var institudeId = sessionStorage.getItem("InstituteId");
var roleId = sessionStorage.getItem("RoleId");
var ref_1 = firebase.database.ref(institudeId + "/Admin/Usertable/");
ref_1.once('value', function(snapshot) {
snapshot.forEach(function(childSnapshot) {
var row= table.insertRows(i);
var x= row.insertCell(0);
var x1= row.insertCell(1);
var x2= row.insertCell(2);
x.innerHTML = childData.status;
x1.innerHTML = childData.totalTimeUsed;
x2.innerHTML = childData.report;
i++;
// ...
});
});
</script>
Everything seems fine to me, except the snapshot.forEach. Before using the values in the snapshot, First extract the values from the snapshot using snapshot.val().
Use snapshot.val().forEach. Hope this will solve your problem.
Note:
The listener receives a snapshot that contains the data at the specified location in the database at the time of the event. You can retrieve the data in the snapshot with the val() method.
I didn't check the table insertion logic as i found that snapshot is used directly.
You need to append the data to the table
$("#userTableInside > tbody").append("" + data for col 1 + "" + data for col 2 + "" + data for col 3 + "");
use the proper variable instead of "data for col 1" etc.
make sure you end with a to indicate the end of the table row.
Do this for each time you loop thru your "children" - basically just replace your code in the same place

Populate 2 tables with 2 sets of data when 1 field matches in both sets

I'm using Josh Fraser's Backwards compatible window.postMessage() (http://www.onlineaspect.com/2010/01/15/backwards-compatible-postmessage) and I'm having trouble.
I have 2 iframes on a page and both iframes send different data to the same parent page. In other words, there are 2 XD.receivemessage functions getting 2 different messages from 2 different iframes. Here's a shortened version of my code:
<iframe id="IFRAME1" src="https://www.DOMAIN.com/PAGENAMEFIRST.php"></iframe>
<iframe id="IFRAME2" src="https://www.DOMAIN.com/PAGENAMESECOND.php"></iframe>
<div id="firstTable">
<table>
<tr>
<th>Name</th>
<th>Address</th>
<th>ID</th>
</tr>
<tr>
<td><!--this will be filled in by the data--></td>
<td><!--this will be filled in by the data--></td>
<td><!--this will be filled in by the data--></td>
</tr>
</table>
</div>
<div id="secondTable">
<table>
<tr>
<th>Email</th>
<th>Twitter Handle</th>
<th>ID</th>
</tr>
<tr>
<td><!--this will be filled in by the data--></td>
<td><!--this will be filled in by the data--></td>
<td><!--this will be filled in by the data--></td>
</tr>
</table>
</div>
<script type="text/javascript">
$(document).ready(function() {
//FIRST DATA PULL
var encodeUriFirst = encodeURIComponent(document.location.href);
var getMessageFirst = 'https://www.DOMAIN.com/PAGENAMEFIRST.php#' + encodeUriFirst;
$("#IFRAME1").attr('src',getMessageFirst);
XD.receiveMessage(function(getMessageFirst){
var getDataFirst = getMessageFirst.data;
var getDataFirstEach = new Array();
for(var a=0; a<getDataFirst.length; a++){
getDataFirstEach = getDataFirst.split("~,~");
$('div#firstTable table td:nth-child(0)').text(getDataFirstEach[0].replace(/[~]/g,""));
}
}, 'https://www.DOMAIN.com');
//SECOND DATA PULL
var encodeUriSecond = encodeURIComponent(document.location.href);
var getMessageSecond = '//www.DOMAIN.com/PAGENAMESECOND.php#' + encodeUriSecond;
$("#IFRAME2").attr('src',getMessageSecond);
XD.receiveMessage(function(getMessageSecond){
var getDataSecond = getMessageSecond.data;
var getDataSecondEach = new Array();
for(var a=0; a<getDataFirst.length; a++){
getDataSecondEach = getDataSecond.split("~,~");
$('div#secondTable table td:nth-child(0)').text(getDataSecondEach[0].replace(/[~]/g,""));
}
}, 'https://www.DOMAIN.com');
});
</script>
Please keep in mind that I've scaled back the code significantly. Each getDataFirst or getDataSecond
It actually works as far as getting the data from both iframes (send/receive both work). My data comes through in the format ~name~,~address~,~ID~ for the first set of data and ~email~,~twitter~,~ID~ for the second set.
I'm trying to get the data to populate the 2 tables. The For loops look for the ID in the table and if the ID matches, it fills in the other fields associated with that ID. In some cases, the ID from the first data set will be the same as the ID from the second data set. When that happens, the for loops place the data in both tables instead of the appropriate one. I'm wondering why this would happen since I'm specifically targeting the table inside either $('div#firstTable') or $('div#secondTable') for the output. For example:
$('div#firstTable table td:nth-child(0)').text(getDataFirstEach[0]);
inside the For loop is placing getDataFirstEach[0] into both the firstTable and secondTable tables?
Can anyone tell me why?
AS REQUESTED, HERE IS THE FULL JS:
var encodeUriGifts = encodeURIComponent(document.location.href);
var giftsMessage = '//www.DOMAIN.org/firstpage.php#' + encodeUriGifts;
$("#IFRAME1").attr('src',giftsMessage);
XD.receiveMessage(function(giftsMessage){
var getDataGifts = giftsMessage.data;
var currentRecordGifts = new Array();
var getGiftsLines = getDataGifts.split("|"); //LINES OF DATA ARE PIPE SEPARATED
for(var bCnt=0;bCnt < getGiftsLines.length;bCnt++){
var getGiftsEach = getGiftsLines[bCnt].split("`,`"); //EACH ITEM IS SEPARATED BY `,`
for(var cCnt=0;cCnt < getGiftsEach.length;cCnt++){
if (getGiftsEach[cCnt]!=="" && getGiftsEach[cCnt]!=="undefined"){
currentRecordGifts[bCnt] = " <td class='giftamount'>"+getGiftsEach[1]+"</td><td class='giftdate'>"+getGiftsEach[2].replace(/[`]/g,"")+"</td>";
}
if (cCnt==2) {
var thisGiftsID = getGiftsEach[0].replace(/[`]/g,"");
$('#firstTable table td:contains("'+thisGiftsID+'")').closest('tr').find('td:nth-child(3)').after(currentRecordGifts[bCnt]);
}
}
if (bCnt==0){
$('#firstTable table th:nth-child(3)').after('<th class="BBListingHeading DirectoryListingHeading" scope="col" style="white-space: nowrap;">Last Gift Amount</th><th class="BBListingHeading DirectoryListingHeading" scope="col" style="white-space: nowrap;">Last Gift Date</th>');
}
}
}, 'https://www.DOMAIN.org');
var encodeUriChanges = encodeURIComponent(document.location.href);
var changesMessage = '//www.DOMAIN.org/secondpage.php#' + encodeUriChanges;
$("#IFRAME2").attr('src',changesMessage);
XD.receiveMessage(function(changesMessage){
var getDataChanges = changesMessage.data;
var currentRecordChanges = new Array();
var getChangesLines = getDataChanges.split("|");
$('#secondTable table tr td:nth-child(3)').each( function() {
$('#secondTable table tr td:nth-child(3)').after('<td class="BBListingItem DirectoryListingItem" style="white-space: nowrap;"><ul class="changes"></ul></td>');
});
for(var dCnt=0;dCnt < getChangesLines.length;dCnt++){
var getChangesEach = getChangesLines[dCnt].split("`,`");
for(var eCnt=0;eCnt < getChangesEach.length;eCnt++){
if (getChangesEach[eCnt]!=="" && getChangesEach[eCnt]!=="undefined"){
currentRecordChanges[dCnt] = "<li class='change'>"+getChangesEach[2]+" ("+getChangesEach[1].replace(/[`]/g,"")+")</li>";
}
if (eCnt==2) {
var thisChangesID = getChangesEach[0].replace(/[`]/g,"");
$('#secondTable table td:contains("'+thisChangesID+'")').closest('tr').find('td ul.changes').append(currentRecordChanges[dCnt]);
}
if (dCnt==0){
$('#changesdiv .DirectoryListingTable th:nth-child(3)').after('<th class="BBListingHeading DirectoryListingHeading" scope="col" style="white-space: nowrap;">Change Details</th>');
}
}
}
}, 'https://www.DOMAIN.org');

Categories