I am new to creating tables with js and started with using document.write. That was writing over my html so now I am using dom elements. How can I id the group of tables so I can position it in my css? I am a little confused how because my code creates multiple tables with the loop. I would just like to position them all as one. The picture shows what they look like but they just default to the bottom/left of my page. Also would appreciate any other code suggestions since I am new at this! Thanks!
<script type="text/javascript">
BuildTable();
function BuildTable() {
var myUrl = window.location.href;
PageMethods.DoStuff(myUrl, onSucess, onError);
function onSucess(result) {
for (var i = 0; i < result.length; i++) {
var body = document.getElementsByTagName("body")[0];
var tbl = document.createElement("table");
var tblBody = document.createElement("tbody");
var row = document.createElement("tr");
var cell = document.createElement("td");
var cellText = document.createTextNode('Community: ' + result[i].apartName);
cell.appendChild(cellText);
row.appendChild(cell);
tblBody.appendChild(row);
row = document.createElement("tr");
cell = document.createElement("td");
cellText = document.createTextNode('Address: ' + result[i].address + ', ' + result[i].city);
cell.appendChild(cellText);
row.appendChild(cell);
tblBody.appendChild(row);
tbl.appendChild(tblBody);
body.appendChild(tbl);
tbl.setAttribute("border", "1");
var space = document.createElement("br");
body.appendChild(space);
}
}
function onError(result) {
alert('Something wrong.');
}
}
</script>
To set the id:
tbl.setAttribute('id', thisTablesId );
But probably what you want is to set the class attribute instead. Those don't need to be unique. You can change the css styles (for positioning) of all tables with the same class at once. Or if you need to programmatically determine the styling, you can use that attribute to determine whether or not this is one of the elements you wanted.
tbl.setAttribute('class', 'built-table' );
In your css stylesheet you can define what the built-table class will include using the .built-table selector.
Related
I generate the set of buttons within html table as follows and then I want to call to function when it click.
$.each(childData, function(key, item) {
var packPath = key.replace(/_/g, "/"); //Replace underscore with slash
div.innerHTML = div.innerHTML + '<td>'+key+'</td>'
+ '<td><button type="button" data-id="'+key+'" class="download btn btn-success btn-xs">Originals</li></td></div>';
})
This is how I call the function but it's not working.
$(".download").click(function(){
alert();
});
Where is the wrong in above code?
Try this:
$(document).on('click', '.download', function(){
// Your Code
});
Delegate the event to static parent:
$(div).on("click", ".download", function(){
Here div can be the static parent which was available when page was loaded at first load. Although document or body can also be used in place of div.
As you have not presented how you create div element but one thing has to be noticed that you are generating an invalid markup. As a td element can't be a child of div but table's tr.
You need to use event delegation.
If your table has an id of "button-table", you can create an event handler like so:
$("#button-table").on("click",function(e){
var target = e.target;
console.log($(target).attr("data-id"));
});
Do you want it this way? I have given code for adding an entire table.Check this out
function generate_table() {
// get the reference for the body
var body = document.getElementsByTagName("body")[0];
// creates a <table> element and a <tbody> element
var tbl = document.createElement("table");
var tblBody = document.createElement("tbody");
// creating all cells
for (var i = 0; i < 2; i++) {
// creates a table row
var row = document.createElement("tr");
for (var j = 0; j < 2; j++) {
// Create a <td> element and a text node, make the text
// node the contents of the <td>, and put the <td> at
// the end of the table row
var cell = document.createElement("td");
var cellText = document.createTextNode("cell in row "+i+", column "+j);
cell.appendChild(cellText);
row.appendChild(cell);
}
// add the row to the end of the table body
tblBody.appendChild(row);
}
// put the <tbody> in the <table>
tbl.appendChild(tblBody);
// appends <table> into <body>
body.appendChild(tbl);
// sets the border attribute of tbl to 2;
tbl.setAttribute("border", "2");
}
<input type="button" value="Generate a table." onclick="generate_table()">
$(document).ready(function() {
$(".download").click(function(){
alert();
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button class="downlaod">Download</button>
I'm attempting to start a div area with html in it and then replace that html with new html. I am currently trying to do so with the use of a function to simplify the creation of the html.
This is my function that creates a table based on input of rows and columns and a character.
function drawArt (x, y, char){
$( "#artArea").append("<table>");
indexY = 0;
while (indexY < y)
{
$( "#artArea").append("<tr>");
var indexX = 0;
while (indexX < x)
{
$( "#artArea").append("<td class=tableCell>" + char + "</td>");
indexX++;
}
$( "#artArea").append("</tr>");
indexY++;
}
$( "#artArea").append("</table>")
};
I'd like to be able to recall this function to redraw the table. So far this is what I have written but it seems to not work. Any tips?
$( "#genNew" ).click(function(){
var xGlobal = $("#numCols").val();
var yGlobal = $("#numRows").val();
var charGlobal = $("#drawChar").val();
$( "#artArea" ).replaceWith();
drawArt (xGlobal, yGlobal, charGlobal);
})
So, as suggested below changing "replaceWith" to "empty" fixed part of my problem. However, it broke another part of my program. I should be able to click on any character and get it to change to whatever was input, without changing the whole table, as so:
$( ".tableCell" ).click(function(){
charGlobal = $("#drawChar").val();
$(this).text(charGlobal)
})
Which part of my program is failing?
The big problem is you're creating invalid html. You always append to the #artArea table, so your markup will end up as
<table>
<tr></tr>
<td></td>
<td></td>
... etc
</table>
This is not what you want. What I suggest you could do is to simply create the appropriate html as a string inside drawArt and use `replaceWith to change the html
function drawArt (x, y, char){
var html = "<table>";
indexY = 0;
while (indexY < y)
{
html += "<tr>";
//-- snip, you get the idea!
}
html += "</table>"
return html;
}
and then
$( "#genNew" ).click(function(){
var xGlobal = $("#numCols").val();
var yGlobal = $("#numRows").val();
var charGlobal = $("#drawChar").val();
$( "#artArea" ).html(drawArt (xGlobal, yGlobal, charGlobal));
})
Working example: http://jsfiddle.net/0sh1wt01/1/
Having updated the question with a new requirement, I should address that too. The reason your click event handler does not work on the table cells is that click only affects elements which are on the page at the time the page loads. if you're dynamically adding new elements (as we are above) then you need to delegate the event to an element which does exist at page load. In this case we could use the artArea. Note you want .html not .text
$( "#artArea" ).on('click','.tableCell', function(){
charGlobal = $("#drawChar").val();
$(this).html(charGlobal);
});
Live example: http://jsfiddle.net/0sh1wt01/2/
You can replace the html with a new one.
This is the js code:
$("#start").click(function() {
var x = $("#rows").val(),
y = $("#columns").val(),
charx = $("#char").val();
//getting teh no of columns, rows and the character
$("#container").html("");
//empty the container first
var table = document.createElement("table");
for (var i = 0; i < x; i++) {
var tr = document.createElement("tr");
for (var j = 0; j < y; j++) {
var td = document.createElement("td");
td.innerHTML = charx;
tr.appendChild(td);
}
table.appendChild(tr);
}
//creating the table based on the values
$("#container").append(table);
//appending inside the container
});
Here is the Plnkr Link
Hope it works for you :)
I need to insert some value into html table dynamically. For example, I have some inputs and then I have a table (about 5 rows), so I have one button which enables a timer. When the timer is stopped I need to insert data into table.
Here is the code, how do I add data to one row?
document.getElementById('d1').innerHTML = document.getElementById('ctrl_ball_size_val').value;
document.getElementById('l1').innerHTML = document.getElementById('ctrl_cilindr_height_val').value;
document.getElementById('t1').innerHTML = document.getElementById('stopwatch').value;
How can I add data (data can be different) to the table row by row?
It is highly recommended to avoid using innerHTML for this task.
I suggest to use the DOM to achieve that.
Here is a quick example on how you can create HTML table dynamically using JavaScript:
var tbl = document.createElement("table");
for(var i=0;i<=10;i++){
var tr = document.createElement("tr");
for(var j=0;j<=10;j++){
var td = document.createElement("td");
td.innerHTML = i*j;
tr.appendChild(td);
}
tbl.appendChild(tr);
}
document.body.appendChild(tbl);
Check out my Live example
If you are using JQuery Simply use:
$('#tableID > tbody > tr').each(function() { //Acess $(this) });
And you Never Need it then?
as per jQuery each loop in table row, just a bit of code:
var table = document.getElementById('tblOne');
var rowLength = table.rows.length;
for(var i=0; i<rowLength; i+=1){
var row = table.rows[i];
//your code goes here, looping over every row.
//cells are accessed as easy
var cellLength = row.cells.length;
for(var y=0; y<cellLength; y+=1){
var cell = row.cells[y];
//do something with every cell here
}
}
First of all, please excuse me as I am a bit new to this so my code does not look pretty... but everything below works, ## this is not a thread asking for help with non working code ##.
Now that thats out of the way... here's the thing: I have made an addon for FF but the addon editor told me it would be rejected as I was using innerHTML... so to change that using appendChild etc, and thats what I did below.
The thing is, it looks ugly and feels really complicated so I was wondering if I used the right approach or is there an easier way of doing this?
var the_table_color,alt_link,link_for_deletion,comment =null;
var xmlDoc=null;
var parser = new DOMParser();
xmlDoc = parser.parseFromString(data, "text/xml");
var nodes = xmlDoc.getElementsByTagName("unblocker_details");
var t = document.createElement("table"),
td = document.createElement("td"),
tr = document.createElement("tr");
var a = document.createElement("a"),
strong = document.createElement("strong");
t.style.width = "80%"; // Table attributes
t.style.border="0";
t.cellspacing="2";
t.cellpadding="2";
for(var i=0; i< nodes.length; i++) {
the_table_color = nodes[i].getAttribute("table_color");
var the_type = nodes[i].getAttribute("type");
alt_link = nodes[i].getAttribute("alt_link");
link_for_deletion = nodes[i].getAttribute("link_for_deletion");
comment = nodes[i].getAttribute("comment");
// TR1, TD1
td=""; td = document.createElement("td");
tr=""; tr = document.createElement("tr");
tr.bgColor=the_table_color;
t.appendChild(tr);
td.width="16%";
td.vAlign="top";
tr.appendChild(td);
strong="";
strong = document.createElement("strong");
strong.appendChild(document.createTextNode(the_type));
td.appendChild(strong);
td.width="16%";
td.vAlign="top";
tr.appendChild(td);
//TD2
td=""; td = document.createElement("td");
td.width="70%";
td.vAlign="top";
a="";a = document.createElement("a");
a.href= alt_link;
a.appendChild(document.createTextNode(alt_link));
a.target= "_blank";
td.appendChild(a);
tr.appendChild(td);
//TD3
td=""; td = document.createElement("td");
td.noWrap="NOWRAP";
td.align="center";
td.vAlign="middle";
td.width="14%";
a="";a = document.createElement("a");
a.href= "javascript:dead_link('"+link_for_deletion+"')";
a.appendChild(document.createTextNode("Dead link?"));
td.appendChild(a);
tr.appendChild(td);
t.appendChild(tr);
// TR2, TD1 (or TD4 in total)
tr=""; tr = document.createElement("tr");
tr.bgColor=the_table_color;
td=""; td = document.createElement("td");
td.vAlign="top";
td.appendChild(document.createTextNode("Comment:"));
tr.appendChild(td);
td=""; td = document.createElement("td");
td.colSpan="2";
td.appendChild(document.createTextNode(comment));
tr.appendChild(td);
t.appendChild(tr);
}// End of for() loop
//alert(t.innerHTML);
document.getElementById("wait").textContent="";
document.getElementById("wait").appendChild (t);
If you don't want to pull in a giant library to do simple stuff you can simply alias the functions:
// aliasing
var el = document.createElement;
// not really aliasing, but I didn't want to modify the prototypes of html elements
function attr(el, attr, value) {
el.setAttribute(attr, value);
}
Changes your code to look something like this:
var td = el('td');
attr(td, 'width', '100%');
Though with jQuery this would look like this:
var td = $('<td>');
td.attr('width', '100%');
Though I'm usually stingy and write a wrapper around jQuery (especially for divs) that tends to look like this:
function div(className) {
if(className) {
return $('<div>', {'class': className});
}
return $('<div>');
}
The ugly thing I see is the setting of attributes without using setAttribute()
If you like to have a kind of snippets, this can be done without using innerHTML, you already use the needed method inside your code.
An simple example that creates a table in 1 step:
var table = parser.parseFromString('<table>'+
'<tr><td>table created without innerHTML</td></tr>'+
'</table>',
'text/xml').documentElement;
JQuery is a lightweight library that does all of what you wish to do in there, and it guarantees cross browser compatibility.
I have the following code:
$(document).ready(function() {
var id = 'cbx';
var idPrefix = 'Arrow';
var html = '<img .../>';
// query parent row
var rowq = $('#' + id);
if (rowq.length < 1) {
rowq = $('.' + id);
VersionHeader = true;
}
if (rowq[0]) {
rowq.addClass('ArrowHeader');
// set to 0 for header
var index = 0;
var row = rowq.parents('.g')[0].insertRow(index);
// assign id for new row
row.id = idPrefix + id;
// assign classes for style and tree
row.className = 'srcrow' + id;
// insert new cell
var cell = row.insertCell(0);
// assign html result
cell.innerHTML = html;
// set colspan
cell.colSpan = 1;
Now my problem is it adds the cell but it adds it under the first column. Is there a way to move through the columns? Granted I'm not an html expert at all. Just a beginner trying to get some stuff to work and would appreciate some help since I'm totally lost. I didn't include the html just ... through it.
Thanks
I'm not sure I'm understanding your question entirely correctly (I gather you are attempting to insert a cell into a new row, and you want to select into which column it is inserted?). Assuming that's what you meant:
row.insertCell(0)
This is your problem. The insertCell method takes as an argument the index of the column into which the cell should be inserted. Index 0 is the first column, index 1 is the second column, and so on. So try replacing the 0 with the appropriate index.