Create dynamic divs using javascript/jquery - javascript

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);
}
}

Related

Using Javascript to embed an onClick event to an HTML div

I'm trying to make an interactable and configurable grid using divs as their cells.
To first give a bit of context on this part of the code, I'm basically just repeating td's in HTML output then appending a specific amount of divs into the td's/rows (cellID is just a method for decorating the div names);
var table, row, div;
table = document.createElement('table');
for (var i=0; i < rows; i++)
{
row = document.createElement('td');
row.id = "row-" + i;
for (var j=0; j < cols; j++)
{
div = document.createElement('div');
div.id = cellID(i, j);
row.append(div);
}
table.append(row);
}
Let's say that:
-rows = 4 and -cols = 2 | The output result on the user's end would be this :
Now my current problem that I'm trying to figure out is how to make every repeated div be given the onClick() event so that an event occurs when you click on the boxes, here is what I tried to make this work :
div.addEventListener("click", null); //This part didn't work for me, though to be honest, I don't really know what to replace the null with
div.getElementById(div.id).onclick = function() { OnClick() }; (OnClick is a test method to see if it works, however this one just rejects an error, saying that "div.getElementById" is not a function, so I don't know what's up with that.)
These things I tried were all things that had been recommended throughout, but I don't know what else could make it work.
What do you think the problem may be there?
-
div.addEventListener() should work.
But you need to create valid DOM structure. Rows are tr, cells are td. You can put the div in the td, or just use the td directly.
let rows = 2,
cols = 4;
var table, row, div;
table = document.createElement('table');
for (var i = 0; i < rows; i++) {
row = document.createElement('tr');
row.id = "row-" + i;
for (var j = 0; j < cols; j++) {
let cell = document.createElement("td");
div = document.createElement('div');
div.id = cellID(i, j);
div.addEventListener("click", function() {
console.log('Clicked on', this.id);
});
div.innerText = div.id;
cell.append(div);
row.append(cell);
}
table.append(row);
}
document.body.appendChild(table);
function cellID(i, j) {
return `cell-${i}-${j}`;
}

jQuery dynamically add images to table

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>

jQuery, adding multiple table rows is not working correctly

The idea is to build a function that takes an input and uses that to build a grid. I'm trying to establish the grid functionality first, and I'm having a peculiar error. I searched for a few hours, but the answers all tell me that a simple "append" should be working.
The specific error that I am getting:
When I load up the webpage, it is only adding one table row to the tbody, and only one table data to that table row. The idea is instead to create a grid of 16 x 16, with 16 rows and 16 data. Console logs show that the loops are all working correctly.
The html is just a basic file that imports the javascript correctly (All tested) with a simple:
div class="container" /div
Code:
$(document).ready(function(){
$(".container").html("");
/*this function makes a table of size numRow and
num data. it then gives each data element
*/
//blank rows to insert
var blankResults = $("<table>");
var result = blankResults;
var row = $("<tr/>");
var data = $("<td/>");
function makeTable(num)
{
result = blankResults;
//create num rows
for (var i = 0; i < num; i++)
{
//for each row
//add data num times
for (var j = 0; j < num; j++)
{
console.log(j);
row.append(data);
}
//append row
console.log(i);
result.append(row);
}
}
//starting area
makeTable(16);
$(".container").append(result);
//Start with 16 by 16 of square divs -
//put inside a container div
});
Try this code.
$(document).ready(function(){
$(".container").html("");
/*this function makes a table of size numRow and
num data. it then gives each data element
*/
function makeTable(num)
{
var output = '<table>';
//create num rows
for (var i = 0; i < num; i++)
{
//for each row
output+= '<tr>'
for (var j = 0; j < num; j++)
{
output += '<td></td>';
}
output += '</tr>';
}
output += '</table>';
return output;
}
//starting area
var result = makeTable(16);
$(".container").append(result);
//Start with 16 by 16 of square divs -
//put inside a container div
});
You are appending to the same variables all the time...row and 'data`. you should not do that.
As you can see from the code below, you need to create the var row = $("<tr>"); on each loop, to reference it when you append the <td> (table cell) to that newly created row.
Modifed to use only one loop:
$(document).ready(function(){
function makeTable(num) {
var table = $("<table>"), row;
for (var i = 0; i < num; i++){
row = $("<tr>");
table.append(row);
row.append(Array(num + 1).join("<td></td>"));
}
return table;
}
$(".container").html(makeTable(16));
});
DEMO PLAYGROUND
Of course, this is not a good way generating a table. running jQuery function on each loop is slow and bad practice. You should generate a big string which will represent your DOM structure and then append that string where needed and jQuery will make a DOM node out of it.
I made up my own html for this but it should be as simple as using two nested for loops grabbing values the size input. Here's what I came up with:
$("#tableMaker").click(function () {
$('.container').html("");
$('.container').append("<table></table>");
for (var i = 0; i < $('#size').val(); i++) {
$('table').append("<tr></tr>");
for (var j = 0; j < $('#size').val(); j++) {
$('tr:last').append("<td>Column " + (j+1) + ", Row " + (i+1) + "</td>");
}
}
})
td {
border: black solid 1px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="number" id="size" placeholder="Size" />
<button id="tableMaker" type="button">Generate Table</button>
<br />
<div class="container">
<div />

How to make a button functional when loaded into a row from local storage in javascript

//loops through all rows and cells and saves them into local storage as objects
window.onbeforeunload = function() {
var rows = document.getElementById('firsttable').tBodies[0].rows;
for (var i = 0; i < rows.length; i += 1) {
localStorage.setItem(i, JSON.stringify({
Item: rows[i].cells[0].innerHTML,
filling1: rows[i].cells[1].innerHTML,
filling2: rows[i].cells[2].innerHTML,
filling3: rows[i].cells[3].innerHTML,
Stock: rows[i].cells[4].innerHTML,
min: rows[i].cells[5].innerHTML,
sold: rows[i].cells[6].innerHTML,
closeAcc: rows[i].cells[7].innerHTML,
sell: rows[i].cells[8].innerHTML,
dltButton: rows[i].cells[9].innerHTML
}));
};
};
//loads the objects into rows with the values in their cells
window.onload = function() {
var r = 0,
c = 0;
//load the actual data from localstorage into html rows
for (x in localStorage) {
var row = table.insertRow(r),
obj = JSON.parse(localStorage.getItem(x));
for (i in obj) {
var cell = row.insertCell(c);
cell.innerHTML = obj[i];
c += 1
}
r += 1;
c = 0;
}
};
//where the problem is
$(function() {
$('table td').click(function(e) {
if (e.target.id === "Sellbtn") {
var sell = prompt("Enter the amount");
for (var i = 0; i < table.length; i += 1) {};
this.parentNode.parentNode.cells[4].innerHTML = parseInt(this.parentNode.parentNode.cells[4].innerHTML) - sell; //not working and no when put inside the for loop it doesn't work idk why
} else if (e.target.id === "Deletebtn") {
return false;
} else {
var ask = prompt("Input");
$(this).html(ask);
}
});
});
So i insert a row and add the details to the cells and such then as explained in the snippet the first function saves available the rows and cells into a JSON stringified object in the localstorage when the user is closing the browser and then loads them up during onload the problem is with the buttons idk how to make them function after the onload(user closes and opens again). So imagine this you have your HTML table with several rows and their cells and each row has the two buttons(sell and delete) how do i make them function when the user opens up the application again? and btw the buttons are both dynamically added using createElement() when the row is originally added
Try delegating the click event you have on your table rows since they're being created after the DOM loads:
$('table').on("click", "td", function(e) {

Search content and creating custom selector filters

I want ckack in table if there are row similar (in column "title 1" and "title 3") get this second row ("tr") background-color: red;.
In the this table both rows in column "title 1" and "title 3" have similar content so second row(if it was more of two rows similar all rows except first row get css.) get css background-color: red;, How is it by jQuery?
Here's a working example: http://jsfiddle.net/vrPNj/1/
And the code:
var vals = [];
var tr = $('tr');
tr.each(function(){
var $this = $(this);
var val = $this.children(':first').text() + $this.children(':last').text();
vals.push(val);
});
for(var i = 0; i < vals.length; i++){
for(var n = 0; n < vals.length; n++){
if(n !== i){
if(vals[i] === vals[n]){
tr.eq(i).addClass('duplicate');
tr.eq(n).addClass('duplicate');
}
}
}
}
tr.filter('.duplicate:first').removeClass('duplicate');
If I am understanding you correctly, this should work:
var rows = [];
$('#your_table tr:eq(1) td').each(function() {
rows.push($(this).text());
});
$('#your_table tr:not(:first)').each(function(i) {
if ($(this).text() != rows[i]) {
$('#your_table tr:eq(0) td:eq(1)').css('background-color', 'red');
return false;
}
});
It's far from optimized, though, so I'll leave that to you.

Categories

Resources