jQuery dynamically add images to table - javascript

I need to add images to a given table. I have the following code:
HTML:
<div class="container" id="game"></div>
Javascript
function table() {
var i,
x,
domRow,
domCol,
rows = $("#rows").val(),
colums = $("#columns").val(),
table = $('<table>'),
cellId = 0;
table.empty();
for(i = 0; i < rows; i++) {
domRow = $('<tr/>');
for(x = 0; x < colums; x++) {
domCol = $('<td/>',{
'id': "cell-" + cellId++,
'class': "cell",
'text': 'cell',
'data-row': i,
'data-col': x
});
domRow.append(domCol);
}
table.append(domRow);
}
return table;
}
Now I want do add images to each data cell from another function.
Example:
function images() {
var game = $("game");
// TODO the images need to be added too
game.append(table())
}
An image with the name 0.png needs to be added to the data cell with the id="cell-0" and so on... (1.png to id="cell-1")
How could I do this?

The jQuery append method can take a function that returns the HTML string to append. And within that function this refers to the element. So you can just find all the td elements in your table and append the right image to each one:
function images() {
var game = $("game");
var tableEl = table();
tableEl.find('td').append(function () {
// `this` is the <td> element jQuery is currently appending to
var num = this.id.split('-')[1];
return '<img src="' + num + '.png" />';
});
game.append(tableEl)
}

Try setting window.myTable or similar to the output of table(), and then edit the table by acessing it from window.myTable.
For adding the images, what I would instead recommend is just inserting:
var img = $('<img>');
img.attr('src', parseInt(cellId) + ".png");
img.appendTo(domCol);
Right before domRow.append(domCol); (I did not test this).

Here is a simple code to add your images in each cell that its id correspond.
$('[id^=cell-]').each(function() {
var curCell = $(this);
curCell.html('<img src="' + curCell.attr('id').substring(5) + '.png">');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<table>
<tr><td id="cell-0">1</td><td id="cell-1">2</td></tr>
</table>

Related

Add images to a div programatically and align them horizontally and vertically

I have 6 images and I want to add those images to a div programatically via javascript or jquery. What is the way to do it? Like I want the alignment to be 2 images in every. So, if there are 6 images, I want 3 rows, each row having 2 mages. Is it possible to without css via js or jquery only .
Also, I would like to add a double click handler to each image added. What is best way to it.
I am looping thru various images like :
for(var i = 0; i < elements.length; ++i) {
if(elements[i].querySelector("img")) {
var path = elements[i].querySelector("img").src;
var newimage = document.createElement('img');
newimage.setAttribute('src', path);
var div = document.getElementById("enclosingdiv");
enclosingdiv.appendChild(newimage);
}
}
You can do it like this-
<div id="imagesDisplay">
</div>
<script>
$(document).ready(function(){
var elements = new Array("book2.jpg","book3.jpg","book4.jpg","book5.jpg");
var noImages = 2; // 2 images per row
var imgCount = 0; // will keep count of images per row
var divHTML = ""; // will hold html tags to be dispalyed once the loop is complete i.e. all the images are added
for(var i = 0; i < elements.length; ++i) {
console.log(elements[i]);
if( imgCount ===0 ) {
divHTML += "<div class='row'>\n";
}
divHTML += "<div class='col-md-6'><img src='images/"+elements[i]+"'></div>\n";
imgCount++;
if( imgCount === noImages) {
imgCount = 0;
divHTML += "</div>\n";
}
}
$("#imagesDisplay").html(divHTML);
});
</script>

Create dynamic divs using javascript/jquery

I would like to create dynamic divs using javascript or jquery and do not really know how to being.
<div id="clickable">
<button class="start">Default</button>
<button class="random">Randon</button>
<button class="gradient">Gradient</button>
<button class="trail">Trail</button>
<button class="clear">Clear</button>
<div id="start">Please click on one of the buttons to get started!</div>
</div>
<div class="wrapper">
</div>
I would like to add the x*x divs between the "wrapper" class. For example, when someone types 4, the output would be a 4x4 grid of divs. Thank you in advance!
Currently I have this, but nothing happens.
$(".start").click(function() {
total = prompt("Please enter a number");
});
$(document).ready(function() {
$(".start").click(function() {
function begin(total) {
for (var i = 0; i < total; i++) {
var rows = document.createElement("div");
for (var i = 1; i < rows; i++) {
var columns = document.createElement("div");
}
}
}
});
});
I have updated a fiddle here to get you started.
The way to get dynamic divs created is to first do the following
Get a handle to your container. In this case it will be $(".wrapper")
I don't know how you wanted the grid to be done, but I've done it by considering each row as one div (with 'n' rows), and each row containing 'n' column divs.
To create a div, you can use the handy $('<div>', {...}) notation. And as you go through the loop, do not forget to append to the container.
Keep the presentation in CSS (you can see that it has been done in the fiddle as well).
The code has been copied here for you to refer to.
$(".start").click(function () {
total = prompt("Please enter a number");
console.log("Total is", total);
//Now call the grid creator.
createGrid(total);
});
function createGrid(total) {
//Get the wrapper handle.
var $container = $(".wrapper");
//Loop through each row.
for (var rowIndex = 0; rowIndex < total; rowIndex++) {
//Create the skeleton for the row.
var rowId = "row-" + rowIndex; //Not needed.
var $row = $("<div>", {
"class": "row",
"id": rowId
});
//Loop through each column
for (var columnIndex = 0; columnIndex < total; columnIndex++) {
//Create skeleton for the column. (Note: IDs have to be unique)
var columnId = rowIndex + "-col-" + columnIndex; //Not needed.
var $column = $("<div>", {
"class": "column",
"id": columnId
});
//Append to the row div.
$row.append($column);
}
//Finally append this row to the container.
$container.append($row);
}
}

inserting row in the middle of a html table using javascript

I have a table which contains two rows.
<tr id="row1"><td>first row</td></tr>
<tr id="row2"><td>second row</td></tr>
I need to insert few rows between row1 and row2 using java script.
I can achieve this by using java script create element. But I wish to add new rows using string html content.
for example :
"<tr><td>This row is placed between first and second</td></tr>".insertAfter(first row Id);
is there way like this to add rows in between?
var newRow = document.createElement("tr");
newRow.innerHTML = "<td>This row is placed... etc.</td>";
var row2 = document.getElementById("row2");
row2.parentNode.insertBefore(newRow, row2);
Read up on it here: https://developer.mozilla.org/en-US/docs/Web/API/Node.insertBefore
Use jQuery. There is a Function insertAfter();
$("#row1").insertAfter("your html");
http://jquery.com/
var button = document.getElementById('insert');
var table = document.getElementById('table');
button.onclick = function() {
var position=Math.round(table.rows.length / 2);
var row = table.insertRow(position);
row.innerHTML = '<td>This row is placed between '+position+' and '+(parseInt(position)+1)+'</td>';
}
**after that if u can use like that u can increment ur row id also:**
var rowId = '#' + tableId + ' tr';
var k = 0;
$(rowId).each(function () {
var ObjInput = $(this).find('input[type=text],input[type=radio],input[type=checkbox],textarea,select,input[type=img],input[type=hidden],input[type=button],img');
if (ObjInput != null) {
for (var j = 0; j < ObjInput.length; j++) {
var inputId = $(ObjInput[j]).attr('id');
inputId = inputId.replace(/_[0-9]{1,2}/g, '_' + k);
$(ObjInput[j]).attr('id', inputId);
$(ObjInput[j]).attr('name', inputId);
}
k++;
}
});

Sorting dynamic table in jquery

Sorry but I'm completly new to js and jquery.
I got dynamic table which values are in localstorage. I can add new row, delete row, and edit cells. This is working.
I want to add a sorting this table by clicked colum. I found here code and try it. It just working when I write table and not use my javascript to add rows from localstorage. Table in two cases looks same in html code. I have no idead why sorting isnt working with dynamic table.
This is w/o my dynamic table from localstore, sorting as supposed to:
http://jsfiddle.net/eW8Kg/1/
This is with table from localstorage(not working in jsfiddle?) on my comupter this is working good, but table is not sorting! (I left this static values):
http://jsfiddle.net/XAu5G/
I think my problem can be in creation of table content:
var Html = "<tbody>";
for (var i = 1; i < localStorage.length; i++) {
var input = "<td><input style='border:hidden' class=\"fields\" name = " + localStorage.key(i) + " type='text' onchange='change(\"" + localStorage.key(i) + "\")' /></td>"
Html += "<tr class=\"field\">";
for (var j = 0; j < 4; ++j) {
Html += input;
}
var button = "<td><input type='button' value = 'UsuĊ„' onclick='Remove(\"" + localStorage.key(i) + "\")'></td>";
Html += button + "</tr>";
}
Html += "<tr id=\"actions\"></tr></tbody>"
document.getElementById("list").innerHTML += Html;
This jquery code do sorting:
$(document).ready(function() {
var table = $('#list');
jQuery.fn.sortElements = (function() {
var sort = [].sort;
return function(comparator, getSortable) {
getSortable = getSortable || function() {return this;};
var placements = this.map(function() {
var sortElement = getSortable.call(this),
parentNode = sortElement.parentNode,
// Since the element itself will change position, we have
// to have some way of storing it's original position in
// the DOM. The easiest way is to have a 'flag' node:
nextSibling = parentNode.insertBefore(
document.createTextNode(''),
sortElement.nextSibling
);
return function() {
if (parentNode === this) {
throw new Error(
"You can't sort elements if any one is a descendant of another."
);
}
// Insert before flag:
parentNode.insertBefore(this, nextSibling);
// Remove flag:
parentNode.removeChild(nextSibling);
};
});
return sort.call(this, comparator).each(function(i) {
placements[i].call(getSortable.call(this));
});
};
})();
$('#x').click(function(){
$('#list').hide();
});
$('#nazwa-header').wrapInner('<span title="sort this column"/>').each(function() {
var th = $(this),
thIndex = th.index(),
inverse = false;
th.on('click', function() {
table.find('td').filter(function() {
return $(this).index() === thIndex;
}).sortElements(function(a, b) {
console.log($(a).find('input').val(),$(b).find('input').val());
return $(a).find('input').val() > $(b).find('input').val() ?
inverse ? -1 : 1
: inverse ? 1 : -1;
}, function() {
// parentNode is the element we want to move
return this.parentNode;
});
inverse = !inverse;
});
});
});

Dynamically selecting column from a html table using jQuery

I have a sample fiddle here which contains a html table with print button. I am printing that whole table as,
function printpage() {
var data = '<table border="1" cellspacing="0"><tr><td colspan="4">Sample Report</td></tr>' + document.getElementsByTagName('table')[0].innerHTML + '</table>';
data += '<br/><button onclick="window.print()" class="noprint">Print the Report</button>';
data += '<style type="text/css" media="print"> .noprint {visibility: hidden;} </style>';
myWindow = window.open('', '', 'width=800,height=600');
myWindow.innerWidth = screen.width;
myWindow.innerHeight = screen.height;
myWindow.screenX = 0;
myWindow.screenY = 0;
myWindow.document.body.innerHTML = data;
myWindow.focus();
}
But I want to include only the columns containing the non zero values in print preview, i.e. something like as follows:
How it is possible?
If I understood correctly, you don't need to remove all cells with 0 values, only those columns where all values are 0.
In your print function add this jquery snippet:
var printableTable = $("table").clone();
var columnLen = printableTable.find("tr:nth-child(1)").find("th").size();
for(var i=1; i<=columnLen; i++)
{
var sum = 0;
printableTable.find("tr td:nth-child("+i+")").each(function()
{
var nr = Number($(this).html());
sum += nr;
});
if (sum == 0)
{
printableTable.find("tr th:nth-child("+i+")").each(function() {
$(this).hide();
});
printableTable.find("tr td:nth-child("+i+")").each(function() {
$(this).hide();
});
}
}
Than use: printableTable.html() instead of document.getElementsByTagName('table')[0].innerHTML
Working demo: http://jsfiddle.net/er144/84tgF/
Well first of all we have to clone that table, and find each td with 0 value.
var table = $("table").clone();
table.find("td").each(function(){
if(!parseInt($(this).text())){
$(this).remove();
}
});
Than we have to remove each td if it's value is 0 and append the cloned table.
var data = '<table border="1" cellspacing="0"><tr><td colspan="4">Sample Report</td></tr>' + table.html() + '</table>';
Here is the updated fiddle http://jsfiddle.net/4d3jj/13/

Categories

Resources