I have a table with few rows, I just need to re arrange them, I am able to fetch <td> and <tr> and now what I need to do is to insert them back in a custom order
$('.white-header').each(function() { //white-header is the class used for <tr>
var tr = $(this);
var td1 = tr.find('td:eq(4)'); // indices are zero-based here
var td2 = tr.find('td:eq(5)');
var td3 = tr.find('td:eq(6)');
var td4 = tr.find('td:eq(7)');
var td5 = tr.find('td:eq(8)');
var td6 = tr.find('td:eq(9)');
var td7 = tr.find('td:eq(10)');
td1.remove();
td2.remove();
td3.remove();
td4.remove();
td5.remove();
td6.remove();
td7.remove();
tr.insert(td7); // here am getting errors, i tried .append also
tr.insert(td6);
tr.insert(td4);
});
i just need to know how to insert td to this tr (currently tr is blank i guess, after removing all td)
You do not need .remove() at all. All you need is to use append and prepend (or appendTo and prependTo) in a clever way to rearrange your cells. These methods do not copy DOM nodes, they move them, so removal is completely unnecessary.
Quick example:
$('.white-header').each(function() {
var tr = $(this);
tr.find('td:eq(4)').appendTo(tr);
tr.find('td:eq(6)').appendTo(tr);
tr.find('td:eq(9)').prependTo(tr);
});
(in my example the order of the elements might seem strange at the end, because I don't run :eq on the original order, but always on the already changed order - this is only a quick example)
You are trying to append the deleted objects, You need to make clone of <td> and remove the <td> objects you have later append the cloned objects of insert
$('.white-header').each(function() { //white-header is the class used for <tr>
var tr = $(this);
var td1 = tr.find('td:eq(4)'); // indices are zero-based here
var td2 = tr.find('td:eq(5)');
var td3 = tr.find('td:eq(6)');
var td4 = tr.find('td:eq(7)');
var td5 = tr.find('td:eq(8)');
var td6 = tr.find('td:eq(9)');
var td7 = tr.find('td:eq(10)');
td1.remove();
td2.remove();
td3.remove();
td4Cloned = td4.clone();
td4.remove();
td5.remove();
td6Cloned = td6.clone();
td6.remove();
td7Cloned = td7.clone();
td7.remove();
tr.insert(td7Cloned); // here am getting errors, i tried .append also
tr.insert(td6Cloned);
tr.insert(td4Cloned);
});
Try using .detach()
$('.white-header').each(function() { //white-header is the class used for <tr>
var tr = $(this);
var td1 = tr.find('td:eq(4)').detach(); // indices are zero-based here
var td2 = tr.find('td:eq(5)');
var td3 = tr.find('td:eq(6)').detach();
var td4 = tr.find('td:eq(7)').detach();
var td5 = tr.find('td:eq(8)');
var td6 = tr.find('td:eq(9)');
var td7 = tr.find('td:eq(10)');
td1.remove();
td2.remove();
td3.remove();
td5.remove();
tr.append(td7); // here am getting errors, i tried .append also
tr.append(td6);
tr.append(td4);
});
Related
I've been attempting to fetch user input value from input fields to later on set it into a summary table that creates cells using javascript but can't seem to get it to work.
Following is my code:
function summonTable(f) {
var sLoc = f.countryf.value();
var eLoc = f.countryt.value();
var sDate = f.sdate.value();
var eDate = f.edate.value();
var div = document.getElementById("summary");
var magicTable = document.getElementById('summaryTable').querySelectorAll('tbody tr'),
var row = document.createElement('tr');
var th = document.createElement('th');
th.textContent = sDate;
var td = document.createElement('td');
td.textContent = sLoc;
//To state which row and column this cell goes to.
row.appendChild(th);
div.appendChild(magicTable);
});
The function summonTable will take in the arguement form f that contains the input fields, I've tried basic textboxes, checkboxes, radios, but all to no avail. The variables sLoc, eLoc are basically texts for countries and sDate, eDate are supposed to be dates.
function summonTable(f) {
var sLoc = f.countryf.value();
var eLoc = f.countryt.value();
var sDate = f.sdate.value();
var eDate = f.edate.value();
var div = document.getElementById("summary");
// to get the last row of the table
var magicTable = document.getElementById('summaryTable').querySelectorAll('tbody tr:last-child'),
var row = document.createElement('tr');
var th = document.createElement('th');
th.textContent = sDate;
var td = document.createElement('td');
td.textContent = sLoc;
//To state which row and column this cell goes to.
row.appendChild(th);
magicTable.after(row); //To add the row after the last row
div.appendChild(magicTable);
});
I created a dynamic table using Javascript. I want to appendChild the cell of each row with a select.
First I tried it using it in a different populateTableCell function after the creation of table is finished. I thought it is better for code readability. But I couldn't succeed.
That's why I tried to populate it in the same function. However, it only populates the very last row.
<table id="informationTable">
<tr>
<th>userID</th>
<th>Status</th>
<th>Profile</th>
</tr>
</table>
Here is the JS I tried...
function setAllUsers(users){
//Create array of options to be added
var array = ["Normal","Incident","Major Incident"];
//Create select list
var selectList = document.createElement("select");
//Create and append the options
for (var i = 0; i < array.length; i++) {
var option = document.createElement("option");
option.value = array[i];
option.text = array[i];
selectList.appendChild(option);
}
for(i = 0; i < users.length-1; i++){
var table = document.getElementById('informationTable');
var row = document.createElement("tr");
row.id = users[i];
var cell0 = row.insertCell(0);
var cell1 = row.insertCell(1);
var cell2 = row.insertCell(2);
cell0.innerHTML = users[i];
cell0.value = users[i];
cell1.id=users[i]+"-status";
cell1.class="statusClass";
cell2.id=users[i]+"-profile";
cell2.class="profileClass";
cell2.appendChild(selectList);
table.appendChild(row);
}
}
I also tried putting the createElement('select'), createElement('option') and select.appendChild(option) inside the "for" loop. But this time page never loads.
I found a similar post and tried to use it.
How to dynamically insert a table row with a select box with options in a table using javascript?
But here each rows are appending due to button click.
Thanks for your answers.
Sincerely,
Alp
Few things:
It probably makes more sense to add a new column instead of appending into the profile cell, so you should add a new column header and run insertCell one more time
You should be using className, not class - class is a reserved word in Javascript.
Unless your users array contains HTML, you should use textContent instead of innerHTML for performance reasons.
You need to run selectList.cloneNode(true) when you append to the cell so that you get a new copy of the element each time.
It is expensive and pointless to run var table = document.getElementById('informationTable'); on each iteration of your loop, you only need to get that handle one time during your function's lifecycle - so move that to the top and outside your loop
I don't have your users array, but here is a working example with a guess on what your array might look like (feel free to replace let and const with var if you need to):
const users = [
['1', 'Active', 'Bob'],
['2', 'Disabled', 'Alice']
];
function setAllUsers(users){
//Create array of options to be added
const priorities = ["Normal","Incident","Major Incident"];
const table = document.getElementById('informationTable');
//Create select list
const selectList = document.createElement("select");
//Create and append the options
for (let i = 0; i < priorities.length; i++) {
const option = document.createElement("option");
option.value = priorities[i];
option.text = priorities[i];
selectList.appendChild(option);
}
for(let i = 0; i < users.length; i++){
const row = document.createElement("tr");
row.id = 'user-'+users[i][0];
const cell0 = row.insertCell(0);
const cell1 = row.insertCell(1);
const cell2 = row.insertCell(2);
const cell3 = row.insertCell(3);
cell0.textContent = users[i][0];
cell1.id = users[i][1]+"-status";
cell1.className = "statusClass";
cell1.textContent = users[i][1];
cell2.id=users[i][2]+"-profile";
cell2.className = "profileClass";
cell2.textContent = users[i][2];
cell3.appendChild(selectList.cloneNode(true));
table.appendChild(row);
}
}
setAllUsers(users)
<table id="informationTable">
<tr>
<th>userID</th>
<th>Status</th>
<th>Profile</th>
<th>Priority</th>
</tr>
</table>
In the following code I need to display months and days in a table. I am able to display months but I can't display days in my table (it contains two headers months and days).
for (var i = 0; i <= result.length; i++) {
var doc = result[i];
var td = $("<td/>").html(doc.Months).data(doc);
var td2 = $("<td/>").html(doc.Days);
var tr = $("<tr>").html(td).append('</tr>');
table.append(tr);
}
<table id="mydemo5" class="mytdemo5" style="display:none;border-collapse: collapse; border-color:white;" border="1">
<tr><th colspan="2">Absence history </th></tr>
<tr><th>Months</th><th>Days</th></tr>
</table>
You are appending only first td, not td2, better to do it this way:
var tr = $("<tr>").appendTo(table); // no need of closing tag, it will be auto handled by jQuery
var td = $("<td>").html(doc.Months).data(doc).appendTo(tr); //No need to assign to var td if it doesn't have any other use
var td2 = $("<td>").html(doc.Days).appendTo(tr);
//table.append(tr) Not needed anymore
I am working on Javascript. I have some API calls (using AJAX) in my code. There is a button in my UI say USER DASHBOARD. On click of this button I am making some API calls using AJAX and displaying HTML UI that has the table with rows in it.
In the table above there are two rows. If I close this popup and then again click on USER DASHBOARD button it will append those two rows again in the table. I don't want to append those rows again.
My code to form table using AJAX response looks like below:
getUserAccountDetailsCallback: function (userid, appid, response) {
if (response != "") {
var res = JSON.parse(response);
var totalNoOfApps = document.getElementById('totalSites');
var totalNoOfSubscriptions = document.getElementById('totalSubscribers');
totalNoOfApps.innerHTML = res.totalNoOfApps;
totalNoOfSubscriptions.innerHTML = res.totalNoOfSubscriptions;
if (res.subscriptionsForCurrentAppId.length > 0) {
for (var i = 0; i < res.subscriptionsForCurrentAppId.length; i++) {
var td1 = document.createElement('td');
td1.style.width = '30';
td1.innerHTML = i + 1;
var td2 = document.createElement('td');
td2.innerHTML = res.subscriptionsForCurrentAppId[i].gatewayName;
var td3 = document.createElement('td');
td3.innerHTML = res.subscriptionsForCurrentAppId[i].priceCurrencyIso;
var td4 = document.createElement('td');
td4.innerHTML = res.subscriptionsForCurrentAppId[i].amountPaid;
var date = new Date(res.subscriptionsForCurrentAppId[i].subscribedDate);
date.toString();
var td5 = document.createElement('td');
td5.innerHTML = date.getMonth() + 1 + '/' + date.getDate() + '/' + date.getFullYear(); //res.subscriptionsForCurrentAppId[i].subscribedDate;
var td6 = document.createElement('td');
td6.innerHTML = res.subscriptionsForCurrentAppId[i].transactionId;
var td7 = document.createElement('td');
td7.innerHTML = res.subscriptionsForCurrentAppId[i].active;
var tr = document.createElement('tr');
tr.appendChild(td1);
tr.appendChild(td2);
tr.appendChild(td3);
tr.appendChild(td4);
tr.appendChild(td5);
tr.appendChild(td6);
tr.appendChild(td7);
var table = document.getElementById('tbl');
table.appendChild(tr);
}
}
}
}
Please help. Where I am doing wrong.
To clean your table, you need to set its HTML content to empty.
Something like this:
var table = document.getElementById('tbl');
table.innerHTML = "";
After that, add your new rows.
You need to empty your table before appending any data to it.
Therefore add this line
table.innerHTML = '';
before table.appendChild(tr); in your code.
This empties your table everytime the function is called.and then append 's new data to it.
If there are any bugs please reply i am happy to help,
Utkarsh Vishnoi
Hi I have code as follows:
function addRowToTable(num){
if (hasLoaded) {
var tbl = document.getElementById(TABLE_NAME);
var nextRow = tbl.tBodies[0].rows.length;
var iteration = nextRow + ROW_BASE;
if (num == null) {
num = nextRow;
} else {
iteration = num + ROW_BASE;
}
// add the row
var row = tbl.tBodies[0].insertRow(num);
// cell
var cell0 = row.insertCell(0);
var LNInpT = document.createElement('input');
LNInpT.setAttribute('type', 'text');
LNInpT.setAttribute('value', 'name');
cell0.appendChild(LNInpT);
// Pass in the elements you want to reference later
// Store the myRow object in each row
row.myRow = new myRowObject(textNode, txtInp, cbEl, raEl);
}}
Please help me to Add new Row before first row in table with editing this code.
tanks
This should help you:
var myTable = document.getElementById('myTable');
var tbody = myTable.tbodies[0];
var tr = tbody.insertRow(-1); // puts it at the start
var td = document.createElement('td');
td.innerHTML = "Something";
tr.appendChild(td);
I'd recommend you use jQuery which will make this much easier (with the prepend method). If you can't or don't want to, you should be able to use insertBefore.
You might want to look at this question on SO.
Use jQuery's prepend() method for that.