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

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.

Related

Adding a new cell to an already existing row

I am new to javascript and I am trying to insert a new cell using only DOM properties and methods into an already existing row without hard-coding or using an index. I am trying to add a new tag. The cell needs to go first because I am adding in formation about that corresponds to that row. Any help would be appreciated. So far I have the following:
var firstTable = document.getElementsByTagName("music
header").nextChild();
console.log(firstTable);
var findRow = firstTable.getElementsByTagName("td");
console.log(findRow);
<div id = "music">
<h2 id = "music header">Music</h2>
<table style="width:100%">
<tr id = "Hard Rock">
<td>NEW CELL HERE</td>
<td>Saint Asonia</td>
<td>Shinedown</td>
<td>Breaking Benjamin</td>
<td>Rise Against</td>
<td>Three Days Grace</td>
</tr>
<tr id = "Metal">
<td>Bullet for my Valentine</td>
<td>Metallica</td>
<td>Korn</td>
<td>Asking Alexandria</td>
<td>Alexisonfire</td>
</tr>
<tr id = "Country">
<td>Toby Kieth</td>
<td>Keith Urban</td>
<td>Taylor Swift</td>
<td>Kenny Chesney</td>
<td>Miranda Lambert</td>
</tr>
</table>
</div>
The code:
var firstTable = document.getElementsByTagName("music
header").nextChild();
console.log(firstTable);
isn't going to work because:
getElementsByTagName expects a tag name, not an ID
getElementsByTagName returns a (possibly empty) collection, not a single element, and that collection doesn't have a nextChild method.
nextChild is not a valid property of any standard DOM object, perhaps you want nextElementSibling, which is a property, not a method
The id "music header" is invalid as the ID attribute value can't contain white space.
To find the first table in the document, you can use:
var firstTable = document.getElementsByTagName('table')[0];
To get the first row of the table, you can use:
var firstRow = firstTable.rows[0];
The index for rows can be any value from 0 to firstTable.rows.length - 1.
To get the first cell of the row:
var firstCell = firstRow.cells[0];
What you do next is up to you…
Since you have the parent element and you've found the first child you can try:
parent.insertBefore(el, parent.firstChild);
Here is the link to the .insertBefore docs on MDN
and here is the docs for firstChild on MDN
It's difficult to know from your question exactly what it is you're trying to achieve. That said, building on Sgnl and RobG's answers and the points the latter made about your structure and references, here is some food for thought.
I assume you want to find the table within a section. You can do that by finding the section first by the id, and then the table beneath that:
var firstTable = document.getElementById("music").getElementsByTagName("table")[0];
Your HTML example implies you then want to add a cell to the first row. You can find that row within the previously found table as so:
var findRow = firstTable.rows[0];
Now that we've found our insert location, let's construct our new cell
var newCell = document.createElement("td");
var newTag = document.createElement("span");
var newText = document.createTextNode("NEW CELL HERE");
newCell.appendChild( newTag );
newTag.appendChild( newText );
With the node built, let's insert it
findRow.insertBefore( newCell, findRow.childNodes[0] );
Here is a working JS Fiddle demonstration

How to get html td cell value by Javascript

I am trying to get the information from my table td's, using javascript. How can i achieve this? I have tried and failed, because i do not exactly understand the JS. So far, i have managed to get one of them to work, which is 'id' but thats just getting info from the db directly, the td values ive been unable to.
echoing the vals in my php update page shows the id val being passed successfully, but none others.
EDIT
Per your last comment I can recommend you use an event listener on all <td> tags and this way you can just get the relevant text of the specific <td> that the user clicked:
var tds = document.querySelectorAll('td');
for (var i = 0; i < tds.length; i++) {
var td = tds[i];
td.addEventListener('click', function(){
console.log(this.innerText)
});
}
<table>
<tr>
<td class="awb">I am the first awb</td>
<td class="awb">I am the second awb</td>
</tr>
<tr>
<td class="differentClass">I am the first differentClass</td>
<td class="differentClass">I am the second differentClass</td>
</tr>
</table>
You are approaching this all wrong...
Instead of this:
var awbno = String(tr.querySelector(".awb").innerHTML);
Do this:
var awbno = document.querySelector(".awb").innerHTML;
Here is a snippet:
var awbno = document.querySelector(".awb").innerHTML;
console.log(awbno);
<table>
<tr>
<td class="awb">Test Text inside a td tag</td>
</tr>
</table>
in order to get the contents of any element using class
let value = document.querySelector('.className').innerHTML;
in order to get the contents of a specific TD
let value = document.querySelector('td.className');

Dynamically create div inside table using jQuery?

I am creating a div dynamically in jQuery as mentioned in the below code appending to the form.
var temp = document.createElement("div");
temp.setAttribute("id", "test");
Form:
<form id="test1" method="get">
</form>
I am trying to have a table created dynamically and need to have this inside a table?
To form table dynamically:
var tableHeader = '<table border="1"> <thead> <tr><th>QueryName</th><th>Description</th><th>Modified Date</th></tr></thead><tbody>';
$("#test").prepend(tableHeader);
Now I need to have <td> (Which I need to create) inside which I need the div element I created. Like this:
<table>
...
....
<tr>
<td>
<div id="test"> // Div i created dynamically in the top(1st line)
</div>
</td>
</tr>
How do I achieve this in jQuery?
Why don't you create the table first?
and then append the table into the dom.
give an id to the td where you want to insert your div.
$('#td-id').html({div-content-goes-here}).
the html() function puts its contents inside the selected dom node.
you can also use append(),
Try the below code:
var temp = document.createElement("div");
temp.setAttribute("id", "test");
console.log(temp);
var tableHeader = '<table border="1"> <thead> <tr><th>QueryName</th><th>Description</th><th>Modified Date</th></tr></thead><tbody>';
$('body').append(tableHeader);
$('table').append(temp);
Also check this JSFiddle and share your thoughts.
To append the div to the td of the table, you must first have such a td. The code below checks its existence and adds it if it doesn't exist.
<form id="test1" method="get"></form>
JavaScript:
var tableHeader = '<table border="1"> <thead> <tr><th>QueryName</th><th>Description</th><th>Modified Date</th></tr></thead><tbody>';
$("#test1").prepend(tableHeader);
if ($('#test1 table tr td:first-child').size()==0) {
console.log('Table has no TDs. Creating a row.');
$('#test1 table tbody').append('<tr><td></td><td></td><td></td></tr>');
}
var temp = document.createElement("div");
temp.setAttribute("id", "test");
temp.appendChild(document.createTextNode('test Div Inserted'));
// appends the DIV to the first TD of the TABLE under #test1 FORM
$('#test1 table tr td:first-child').append(temp);
JSFiddle Demo.
#user2067567, here is a healthy approach, put an id on your dynamic table, before you append it to the DOM...
var tableHeader = '<table border="1" id="mtableid"> <thead> <tr><th>QueryName</th><th>Description</th><th>Modified Date</th></tr></thead><tbody>';
...Then make your base point for manipulating your new table from this ID...
var mtable = $('#mtableid');
...Then look for the tr row you want to enter...
var firstrow = mtable.find('tr').eq(1);
...Then append content to the first row...
$('<td><div>...</div></td>').appendTo(firstrow);
This is all untested, but posted just to give you a general idea.
Let me know if you want further details.
var temp = document.createElement("div");
temp.setAttribute("id", "test");
var tableHeader = '<table border="1"> <thead> <tr><th>QueryName</th><th>Description</th><th>Modified Date</th></tr></thead><tbody>';
$("#test1").prepend(tableHeader);
$('tr').append(temp);
$('div').html('create div content');
the answer to your question is quite simple but there is an important point that you've missed to explain. Which tr do you want to append to. Do you want to create a new tr for every div you want to append to the table or is there some other logic?

How to make a table with rows that can be copied (adding a new row after that one, containing the same) with Javascript?

I am trying to make a table containing several rows, each with a button in the last cell that creates a copy of the row.
All the other cells contains an input (text).
The content (value) of the inputs that are added must be the same as the one above (the one they are copies of).
The copies cannot be copied however!
The inputs must have a unique name something like this:
1-1-name
1-1-age
1-1-country
1-1-email
and if this row is copied, the copied inputs must have names like this
1-2-name
1-2-age
1-2-country
1-2-email
The next one with 3 instead of 2, and so on.
The problem with this, I guess, is that I must do this without JQuery. I can only use Javascript. Is this even possible?
Take a look at this fiddle. Here is a pure js (no-jQuery) way to duplicate a table row and increment it's ID:
var idInit;
var table = document.getElementById('theTable');
table.addEventListener('click', duplicateRow); // Make the table listen to "Click" events
function duplicateRow(e){
if(e.target.type == "button"){ // "If a button was clicked"
var row = e.target.parentElement.parentElement; // Get the row
var newRow = row.cloneNode(true); // Clone the row
incrementId(newRow); // Increment the row's ID
var cells = newRow.cells;
for(var i = 0; i < cells.length; i++){
incrementId(cells[i]); // Increment the cells' IDs
}
insertAfter(row, newRow); // Insert the row at the right position
idInit++;
}
}
function incrementId(elem){
idParts = elem.id.split('-'); // Cut up the element's ID to get the second part.
idInit ? idParts[1] = idInit + 1 : idInit = idParts[1]++; // Increment the ID, and set a temp variable to keep track of the id's.
elem.id = idParts.join('-'); // Set the new id to the element.
}
function insertAfter(after, newNode){
after.parentNode.insertBefore(newNode, after.nextSibling);
}​
<table id="theTable">
<tr id="1-1">
<td id="1-1-name"><input type="text"/></td>
<td id="1-1-age"><input type="text"/></td>
<td id="1-1-country"><input type="text"/></td>
<td id="1-1-email"><input type="text"/></td>
<td id="1-1-button"><input type="button" value="Copy"/></td>
</tr>
</table>​
Edit: Updated to insert the new row after the clicked one. Now with buttons and inputs!
Yes this is possible,
you should create a new table row ,
then set its innerHTML to the innerHTML of the row above.
jQuery is a JavaScript library, which means it is built with JavaScript functions.
So everything you can do with jQuery, you can do with JavaScript too.
Léon

javascript, dynamic id for table:how to recognize?

In my application i use a framework that generates a table with the id of the cells at Run-Time in ascending order.
So that i have "ElementX1X1" for row1 and column1, "ElementX1X2" for row1 and column2 etcetc...
The HTML structure generated will be:
<tr>
<td class="my_msg" align="left">
<id="ElementX1X1">
what i can set is the class(my_msg) and the content of the cell(of the table).
I want simply make:
var test=document.getElementById("ElementX1X1");
test.onclick=function();
but i'm not able to recognize the cell...
i want to make getElementById only if it is in the class "my_msg" or only if it has a certain content(as i said the only two things i can set)...
Anyone has any idea on how i can solve the problem?!
Thanks in advance!
Update the HTML to:
<td id="ElementX1X1" class="my_msg" >...
Edited - to work around broken framework:
<tr>
<td class="my_msg" align="left">
<id="ElementX1X1">
some content
</td>
<td class="my_msg" align="left">
<id="ElementX1X2">
some content
</td>
</tr>
If you want to find row 1 column 2, you can cheat using a bit of jQuery to inspect the contents of the element:
var row = 1;
var column = 2;
var matched = null;
$(".my_msg").each({
if($(this).html().indexOf('<id="ElementX' + row + 'X' + column + '">')!=-1){
matched = $(this);
}
});
matched will either point to the element you're looking for or null - but if you already know the row and column id's of the cells then why not just walk the DOM?
var row = 1;
var column = 2;
var matched = null;
var table = document.getElementsByTagName("TABLE")[0]; // up to you how your find it
try {
matched = table.getElementsByTagName("TR")[row-1].getElementsByTagName("TD")[column-1];
}
catch(err) {
// not found
}
Or the brute force way (i.e. fix the framework output):
var table = $("#tableid"); // up to you how your find it
table.html(table.html().replace(/">\n<id="/g,'" id="'));
your code is now:
<tr>
<td class="my_msg" align="left" id="ElementX1X1">…</td>
<td class="my_msg" align="left" id="ElementX1X2">…</td>
…
so you can use
$("#ElementX2X1");
to select the first row, second column
Neither is particularly elegant, but should get the job done while you wait for your buggy framework to be fixed ;)

Categories