DOM Add Table Row Where I Want It [duplicate] - javascript

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
How to do insert After() in JavaScript without using a library?
Currently this script adds a row at the bottom of the table. How do I tell it to add it after a particular row? At the top of the table?
<script>
var i = 1;
function changeIt() {
var tr = document.createElement('tr');
var td = tr.appendChild(document.createElement('td'));
td.style.valign = 'middle';
var span = td.appendChild(document.createElement('span'));
span.style.fontWeight = 'bold';
span.appendChild(document.createTextNode('URL ' + i));
td = tr.appendChild(document.createElement('td'));
var input = td.appendChild(document.createElement('input'));
input.name = 'url' + ++i;
input.type = 'text';
input.size = '40'
document.getElementById('myTable').tBodies[0].appendChild(tr);
}
</script>
I've been searching Google to learn, but I keep coming across jQuery, innerhtml, and insertrow answers.

You're looking for node.insertBefore() https://developer.mozilla.org/en-US/docs/DOM/Node.insertBefore
var i = 1;
function changeIt() {
var tr = document.createElement('tr');
var td = tr.appendChild(document.createElement('td'));
td.style.valign = 'middle';
var span = td.appendChild(document.createElement('span'));
span.style.fontWeight = 'bold';
span.appendChild(document.createTextNode('URL ' + i));
td = tr.appendChild(document.createElement('td'));
var input = td.appendChild(document.createElement('input'));
input.name = 'url' + ++i;
input.type = 'text';
input.size = '40'
var node = document.getElementById('myTable').tBodies[0];
node.insertBefore(tr, node.firstChild);
}
To add to a specific position you will need to know the index in the .children. Otherwise some key identifier (class name, attribute, or ID), something you can pass into a getBy or QSA.

Related

Element inside loop having last loop value for all ids [duplicate]

This question already has answers here:
JavaScript closure inside loops – simple practical example
(44 answers)
Closed 5 years ago.
I have a while loop that loops 6 times, each time its loops a TD element is create as well as setting an id to it, the problem im having is that the id for everysingle one of the TDs is having the last result of the loop.
var table = document.getElementById("table_calendar");
var tr = document.createElement("tr");
var td;
var days_displayed = 1;
while(i<=6){
td = document.createElement("td");
td.innerHTML = days_displayed;
td.classList.add("tdd");
td.id = year+"-"+month +"-"+days_displayed;
console.log(days_displayed);
td.onclick = function(){
alert(td.id);
};
days_displayed++;
i++;
tr.appendChild(td);
}
table.appendChild(tr);
The alert function is showing this for any TD that I click 2018-02-6
The innerHTML is having different values such as 1 2 3 4 5 6
Am I missing something?
You should access the id of the HTML element using this:
var table = document.getElementById("table_calendar");
var tr = document.createElement("tr");
var td;
var days_displayed = 1;
var year = "2028"
var month = "02"
var i = 0
while(i<=6){
td = document.createElement("td");
td.innerHTML = days_displayed;
td.classList.add("tdd");
td.id = year+"-"+month +"-"+days_displayed;
console.log(days_displayed);
td.onclick = function(){
alert(this.id);
};
days_displayed++;
i++;
tr.appendChild(td);
}
table.appendChild(tr);
<table>
<tr id="table_calendar">
</tr>
</table>
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/this
What happens here is that your td.id will return the last element created, because it has been declared as a var outside the loop. The scope of var is not limited to the block inside {}. If you want the variable to be block scoped you have to use let instead:
var table = document.getElementById("table_calendar");
var tr = document.createElement("tr");
var days_displayed = 1;
var year = "2028"
var month = "02"
for(let i = 0; i <= 6; i++){
let td = document.createElement("td");
td.innerHTML = days_displayed;
td.classList.add("tdd");
td.id = year+"-"+month +"-"+days_displayed;
console.log(days_displayed);
td.onclick = function(){
alert(td.id);
};
days_displayed++;
tr.appendChild(td);
}
table.appendChild(tr);
<table>
<tr id="table_calendar">
</tr>
</table>
What's the difference between using "let" and "var" to declare a variable?
Greetings

Creating dynamically large table using JavaScript

I'm trying to create dynamically a table using JavaScript.
Here is the code I'm using (or here http://liveweave.com/mqG5iT):
function Process(){
CreatTable(['First Name', 'Last Name', 'Email']);
}
function CreatTable(data) {
var checkbox;
var table;
var thead;
var tr;
var th;
var tbody;
tablearea = document.getElementById('ShowDataID');
table = document.createElement('table');
table.id = "ContactsTable";
thead = document.createElement('thead');
tr = document.createElement('tr');
tbody = document.createElement('tbody');
//create columns input checkbox column
checkbox = CreateHTMLElement("chkBoxAllEmails", "chkBoxAllEmails", "SelectAllEmails()", "checkbox", "false");
th = document.createElement('th');
th.appendChild(checkbox);
tr.appendChild(th);
thead.appendChild(tr);
//create columns FirstName,LastName,Emails
for (var i = 0; i < data.length; i++) {
var headerTxt = document.createTextNode(data[i]);
th = document.createElement('th');
th.appendChild(headerTxt);
tr.appendChild(th);
thead.appendChild(tr);
}
table.appendChild(thead);
//create rows and addind to table
for (var i = 0; i < 2000; i++) {
tr = document.createElement('tr');
checkbox = CreateHTMLElement("11", "11", "11", "checkbox", "11");
tr.appendChild(document.createElement('td'));
tr.appendChild(document.createElement('td'));
tr.appendChild(document.createElement('td'));
tr.appendChild(document.createElement('td'));
tr.cells[0].appendChild(checkbox); tr.cells[1].appendChild(document.createTextNode('John'+i.toString()));
tr.cells[2].appendChild(document.createTextNode('McDowell'));
tr.cells[3].appendChild(document.createTextNode('ddd#gmail.com'));
tbody.appendChild(tr);
table.appendChild(tbody);
}
document.getElementById("TablePagingArea").appendChild(table);
//return table;
}
function CreateHTMLElement(id, name, onclick, type, value) {
var HTMLElement = document.createElement('input');
HTMLElement.id = id;
HTMLElement.name = name;
HTMLElement.onclick = onclick;
HTMLElement.type = type;
HTMLElement.value = value;
return HTMLElement;
}
With a small set of data 1000-3000 rows it works relatively well but, some of the data set contains upwards of 5000 rows which causes Firefox to crash and close or become unresponsive.
My question is: is there a better way to accomplish what I am trying to do?
Most efficient way to create a bunch of elements is to create a string and create element from this string.
Most efficient way to create a string of element is to join from array
So you should refactor your code to
Create an array of elements like a[i] = "<tr><intput type='checkbox'></tr>";
Join an array to get one string var s = a.join();
Create DOM elements like var div = document.createElement('div'); div.innerHTML = s;

functions for checkboxes in Javascript

So I have a code with check boxes and I need a suggestion for a function to get data from database if the check box is checked. The table name for the database is Shifliigid and the column name which data I use in the check box is shiffer. So any suggestions would be nice (English isn't my first or even second language, so don't be mad for the short and shady explanation)
var nodeTr = document.createElement("tr");
var td_tekst = document.createElement("td");
td_tekst.innerHTML="Motoorika";
var td = document.createElement("td");
td.style.width = "370px";
var input = document.createElement("textarea");
//input.type = "text";
input.name = "//funktsioonide hindamine/funktsioon[" + count + "]/motoorika";
input.value = rowData.motoorika.replace(/<br\/>/g, "\r\n");
input.className = "txt_left";
input.style.width = "368px";
input.style.fontSize = "9pt";
var nodeMotoorika = input;
addChangeListener(input);
td.appendChild(input);
nodeTr.appendChild(td_tekst);
nodeTr.appendChild(td);
evaluationContainer.appendChild(nodeTr);
//This is the part that makes the checkboxes
var nodeTr = document.createElement("tr");
var td_tekst = document.createElement("td");
var td = document.createElement("td");
var echeckbox = document.createElement("input");
echeckbox.type="checkbox";
echeckbox.name = "//funktsioonide hindamine/funktsioon[" + count + "]/nagemine/vahend_0301";
td.appendChild(echeckbox);
td.innerHTML+="käeprotees/-ortoos";
nodeTr.appendChild(td_tekst);
nodeTr.appendChild(td);
evaluationContainer.appendChild(nodeTr);
var nodeTr = document.createElement("tr");
var td_tekst = document.createElement("td");
td_tekst.innerHTML="Liikumine";
var td = document.createElement("td");
td.style.width = "370px";
var input = document.createElement("textarea");
//input.type = "text";
input.name = "//funktsioonide hindamine/funktsioon[" + count + "]/liikumine";
input.value = rowData.liikumine.replace(/<br\/>/g, "\r\n");
input.className = "txt_left";
input.style.width = "368px";
input.style.fontSize = "9pt";
var nodeLiikumine = input;
addChangeListener(input);
td.appendChild(input);
nodeTr.appendChild(td_tekst);
nodeTr.appendChild(td);
evaluationContainer.appendChild(nodeTr);
//This is the part that makes the checkboxes
var nodeTr = document.createElement("tr");
var td_tekst = document.createElement("td");
var td = document.createElement("td");
var echeckbox = document.createElement("input");
echeckbox.type="checkbox";
echeckbox.name = "//funktsioonide hindamine/funktsioon[" + count + "]/nagemine/vahend_0302";
td.appendChild(echeckbox);
td.innerHTML+="jalaprotees/-ortoos";
nodeTr.appendChild(td_tekst);
nodeTr.appendChild(td);
evaluationContainer.appendChild(nodeTr);
There is no JS "function to get data from database".
You will have to choose a backend technology to access the database. For example PHP.
Use ajax calls to get the data from database using PHP or asp.
You can check if a particular checkbox is checked using the checked property of DOM.

Adding ledger totals in multiple TDs

This code generates a ledger. I narrowed it down to the minimum. By clicking a plus sign it adds an additional row to the ledger.
I'm looking to add each total of the variable newAmount and locate its updated total in a TD to the right of each row. I created newAmount.id = "mainAmount"; to create unique IDs thinking this would help.
var mainNumber = 0;
function addElement()
{
//add a number for each row
mainNumber++;
//create each row, id each slot, and add it where it goes
newDiv = document.createElement("div");
newDiv.id = "main";
newTable = document.createElement("table");
newTable.id = "mainTable";
newDiv.appendChild(newTable);
newTr = document.createElement("tr")
newTr.id = (mainNumber);
newTr.className = "mainRow";
newTable.appendChild(newTr);
newAmount = document.createElement("td");
newAmount.id = "mainAmount";
newAmount.className = (mainNumber);
newPlus = document.createElement("td");
newPlus.id = "mainPlus";
newTotalTable = document.createElement("table");
newDiv.appendChild(newTotalTable);
newTotalTable.id = "mainTotalTable";
newTotalTr = document.createElement("tr");
newTotalTable.appendChild(newTotalTr);
newTotalTr.id = "mainTotalTr";
newTotalTd = document.createElement("td");
newTotalTd.id = "mainTotalTd" + (mainNumber);
newTr.appendChild(newAmount);
newTotalTr.appendChild(newTotalTd);
//whats default inside of each slot
newAmount.innerHTML = '<form name="formAmount"><textarea name="textAmount" size="25" onfocus="wait();" id="amount' + (mainNumber) + '">0</textarea>';
newTr.appendChild(newPlus);
//click this to add a row
newPlus.innerHTML = '<img src="images/plus.png">';
// add the newly created element and it's content into the DOM
my_div = document.getElementById("mainAnchor");
document.body.insertBefore(newDiv, my_div);
}
//doesn't work...trying to hover over any row and show var idName in console
function trHover(){
$('tr').hover(function() {
var idName = $('tr'+'#'+(mainNumber)).attr('id');
console.log(idName);
});
}
//when you focus on amount box, this is activated, which adds attribute onblur and stars addTotal
function wait(){
var blurred = $(this).attr("onblur");
blurred = addTotal();
}
//adds total and displays it in td to the right
function addTotal(){
var y = 1;
var sum = 0;
var input;
while( ( input = document.getElementById( 'amount'+y ) ) ) {
sum += parseInt( input.value );
++y;
console.log(sum);
$("#mainTotalTd1").text(sum);
}
}
Rather than adding a single row, it looks like clicking the plus sign adds a div and two tables, so I'm not sure what you are going for there. I can fix the hover function, though:
$('tr').hover(function() {
var idName = $(this).attr('id'); // 'this' is the element being hovered
console.log(idName);
});

JavaScript/DOM - Give a newly created element an ID

How can I apply an element ID to a newly created element through JavaScript DOM?
The code I have written creates a table which is triggered from a button.
I need to apply a unique ID to this table so it can be styled differently to others which appear on my site.
Here is a sample of my code:
var tab = document.createElement("ViewShoppingCart");
document.getElementById("shopping_list").appendChild(tab);
var tbdy = document.createElement("tbody");
tab.id = "new_cart";
tab.appendChild(tbdy);
new_cart = true;
var total = 0;
for (var a = 0; a <= nameArray.length-1; a++) {
var tr = document.createElement("tr");
tbdy.appendChild(tr);
var td = document.createElement("td");
td.appendChild(document.createTextNode("x " + quantityArray[a]));
tr.appendChild(td);
var td2 = document.createElement("td");
td2.appendChild(document.createTextNode(nameArray[a]));
tr.appendChild(td2);
var td3 = document.createElement("td");
td3.appendChild(document.createTextNode(sumArray[a]));
tr.appendChild(td3);
}
Try
var tbdy = document.createElement("tbody");
tbdy.id = "newtbodyid";
tab.id = "new_cart";
tab.appendChild(tbdy);
new_cart = true;
For applying styles consider using class selectors, you may not need IDs at all.
Note that if you want to create valid HTML you can't have duplicated IDs that significantly lessens value for CSS styles, especially for table data.

Categories

Resources