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?
Related
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.
I have existing table where I would like to add/append tbody element. Here is example of my HTML table:
<div id="myDiv">
<table class="myTable">
<thead>
<tr>
<th>ID</th>
<th>Last</th>
<th>First</th>
<th>DOB</th>
<th>Nickname</th>
</tr>
</thead>
</table>
</div>
Here is my JavaScript/JQuery code:
var divID = $('#myDiv table.myTable');
var tbl = "<tbody>";
for(var i=0; i < numRecs; i++){
var jsRec = obj.DATA[i];
tbl += "<tr id='lookup_"+i+"'>";
tbl += "<td>"+decodeURIComponent(jsRec.ID)+"</td>";
tbl += "<td>"+decodeURIComponent(jsRec.LAST)+"</td>";
tbl += "<td>"+decodeURIComponent(jsRec.FIRST)+"</td>";
tbl += "<td>"+decodeURIComponent(jsRec.DOB)+"</td>";
tbl += "<td>"+decodeURIComponent(jsRec.NICKNAME)+"</td></tr>";
}
tbl += "</tbody>";
divID.append(tbl);
$.alert(divID,'Main Menu',1000,600); //JQuery dialog box that takes html variable, title, width and height
I'm getting blank content in my dialog box with this code. If anyone can help or see where is my code breaking please let me know. Thank you.
It looks like you're not closing the <tr> in your loop, making a series open-ended table-rows. jQuery validates HTML before appending into the DOM so it's likely silently failing when trying to append.
I would separate the creation of elements in small chunks a shown in the following example. That way it would be easier to separate were things are going south. You´ll probably only need to replace sampleData[i]["id"] with decodeURIComponent(jsRec.ID), etc. I only created the sampleData Array for the examples sake. It might also be possible to execute decodeURIComponent() for each of the properties of your object inside a loop.
(function($) {
$(document).ready(function() {
var sampleData = [{
id: 1,
last: "lst",
first: "first",
DOB: "IDK",
nickname: "nick"
}];
var divID = $('#myDiv table.myTable tbody');
var current, row, cell;
for (var i = 0; i < sampleData.length; i++) {
row = $("<tr></tr>"); //Create a row
cell = $("<td></td>").html(sampleData[i]["id"]); //Create a cell
row.append(cell); //Append The cell
cell = $("<td></td>").html(sampleData[i]["last"]);
row.append(cell);
cell = $("<td></td>").html(sampleData[i]["first"]);
row.append(cell);
cell = $("<td></td>").html(sampleData[i]["DOB"]);
row.append(cell);
cell = $("<td></td>").html(sampleData[i]["nickname"]);
row.append(cell);
divID.append(row); //Add Row to the Table
}
});
})(jQuery);
td,
th,
tr {
border: 1px solid gray;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id="myDiv">
<table class="myTable">
<thead>
<tr>
<th>ID</th>
<th>Last</th>
<th>First</th>
<th>DOB</th>
<th>Nickname</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
</div>
At the end you might have trouble with $.alert(divID,'Main Menu',1000,600); but all you might need is to add a toString() or something like that.
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
I'm looking to retrieve the text inside a HTML table that is rendered via a webgrid. The text that I want is located inside a div with the class productID. My starting reference point is in the same row but the last td with the class span2. I'm trying to use jQuery's closest() method however I'm not getting any value returned.
Please see below for a section of the rendered HTML and my jQuery function:
HTML:
<tr>
<td class="span1"><div class="productID">1</div></td>
<td class="span2">Listing</td>
<td class="span2">Full Districtution</td>
<td class="span2">$1,350.00</td>
<td class="span2">2016-01-01</td>
<td class="span2"><div title="This is my brand new title!" data-original-title="" class="priceToolTip">2016-04-30</div></td>
<td>Select</td>
</tr>
jQuery:
$(".priceToolTip").mouseover(function () {
var row = $(this).closest("span1").find(".productID").parent().find(".productID").text();
console.log("Closest row is: " + row);
});
The .closest() method looks for a match in the ancestors. So you can use it to grab the tr then look for .productID like so:
var productID = $(this).closest('tr').find('.productID').text();
Or:
var productID = $(this).parent().find('.productID').text();
Or:
var productID = $(this).siblings('.span1').find('.productID').text();
.span1 is not the closest element of .priceToolTip. Use closest("tr").find(".span1 .productID") like following.
$(".priceToolTip").mouseover(function () {
var row = $(this).closest("tr").find(".span1 .productID").text();
console.log("Closest row is: " + row);
});
I am just doing a Javascript excercise which should add a row into a table. Html reads like this:
<!DOCTYPE html>
<html><head><br><meta charset=utf-8 />
</head><body>
<table id="sampleTable" border="1">
<tr><td>Row1 cell1</td>
<td>Row1 cell2</td></tr>
<tr><td>Row2 cell1</td>
<td>Row2 cell2</td></tr>
</table><br>
<input type="button" onclick="insert_Row()" value="Insert row">
</body></html>
And my script that doesn't work:
function insert_Row(){
var xTable=document.getElementById('sampleTable');
for (i=0;i<=xTable.children.length;i++)
{
if(i===xTable.children.length)
{
xTable.createElement('tr');
tr.innerHTML ='<td>cell1</td><td>cell2</td>'
}
}
}
This is the correct solution:
function insert_Row()
{
var x=document.getElementById('sampleTable').insertRow(0);
var y = x.insertCell(0);
var z = x.insertCell(1);
y.innerHTML="New Cell1";
z.innerHTML="New Cell2";
}
I would like to understand what is wrong with my first solution? Why doesn't it create the tag but throws error instead?
You never add the row to the table. The createElement does not attach itself to anything. You would need to use appendChild() or insertBefore()
var table = document.getElementById("sampleTable"),
tbody = table.getElementsByTagName("tbody")[0];
for (var i=0;i<5;i++) {
var row = document.createElement("tr");
var cell1 = document.createElement("td");
var cell2 = document.createElement("td");
cell1.innerHTML = i + "- 1";
cell2.innerHTML = i + "- 2";
row.appendChild(cell1);
row.appendChild(cell2);
tbody.appendChild(row);
}
<table id="sampleTable" border="1">
<tbody>
<tr>
<td>Row1 cell1</td>
<td>Row1 cell2</td>
</tr>
<tr>
<td>Row2 cell1</td>
<td>Row2 cell2</td>
</tr>
</tbody>
</table>
your xTable.createElement is not creating any child element.The actual method is document.createElement().There is no element.createElement
again parentnode.children is accessing only the elements which is a direct children of table element which is tBody element.So, parentnode.children.length is equal to 1 here.But it will increase after adding another tr element as it was not added to tbody element.Thus it makes the for loop infinite.I will discuss it shortly.
also you have to use element.appendChild() method to appedn the child you
have already created.To add table cells don't use innerHTML,rather
use dom methods to do this things for you
The for loop in your code is getting infinite, because after adding one tr element to your table, xTable.children.length is increased by one.So,every time the for loop is executed it finds that the length is increased and after adding another tr element it increases once again. So,it never gets any chance to break.Thus become infinite loop.So careful when using for loop to add element to table
var xTable=document.getElementById('sampleTable');
var tr=document.createElement('tr');
tr.innerHTML ='<td>cell1</td><td>cell2</td>'
xTable.appendChild(tr);
The first error, in execution, is that you try to call xTable.createElement. Element nodes do have a createElement method; document nodes do, so you would need to use document.createElement('tr') instead. And you need to assign its return value to a variable in order to do anything with the newly created element.
Moreover, you need to add the element to the document tree. If you add it to the table, there is a problem. You have loop that traverses all the children of the table, and appending a new child would make the loop infinite. The loop is actually not needed at all. To find the last child, you need not traverse all children; you just use the children.length property. But you don’t need even that; to append a row (which is what you are doing here, not really inserting), you simply call the appendChild method of the prospective parent.
There’s more. In HTML (strictly speaking, in HTML linearization only, not in XHTML linearization), a tr element is not a child of table. Browsers will insert tbody elements when needed so that a tr is a child of a tbody which is a child of table. This means that the value of xTable.children.length is 1; the table has just one child, a tbody element.
Thus, using the approach in your first code can be properly coded as follows:
<table id="sampleTable" border="1">
<tr><td>Row1 cell1</td>
<td>Row1 cell2</td></tr>
<tr><td>Row2 cell1</td>
<td>Row2 cell2</td></tr>
</table>
<p><input type="button" onclick="insert_Row()" value="Insert row">
<script>
function insert_Row(){
var xTable = document.getElementById('sampleTable');
var tr = document.createElement('tr');
tr.innerHTML = '<td>cell1</td><td>cell2</td>';
xTable.children[0].appendChild(tr); // appends to the tbody element
}
</script>
Tables are special. They have special (optional) methods to add children. TABLE has insertRow and TR has insertCell. They're especially useful if you want to add the row/cell somewhere not at the end.
Setting a TR's innerHTML should work on most browsers, but probably not all.
(If you're building an entire table, create the HTML in JS and then set an innerHTML. It's much faster than creating separate TR and TD.)