I have this code below that prints the value of random fruits table whenever i click the cell value. The problem is i'm trying to create a function that allows me to move the value of random fruits table into the red fruits table by clicking on for example kiwi and it will move into the red fruits table and also i want to be able to move back that value i moved into red fruits table back to the random fruits table. I tried to do it using the array push method but it only copies the value into the other table and not completely move it. Is there any easy way to do this any suggestion would be greatly appreciated thanks!
var obj = {};
var obj2 = {};
var key = "Red Fruits";
obj[key] = ['Apple', 'Cherry', 'Strawberry'];
var myArray = [];
myArray.push(obj);
var key2 = "Green Fruits";
obj[key2] = ['Watermelon', 'Durian', 'Avacado'];
var myArray2 = [];
myArray2.push(obj);
var key3 = "Random Fruits";
obj2[key3] = ['Kiwi', 'Pomegranate', 'Honeydew', 'Plum'];
var myArray3 = [];
myArray3.push(obj2);
var $header = $("<tr>"),
cols = 0,
bodyString = "";
$.each(obj, function(key, values) {
cols = Math.max(cols, values.length);
$header.append($('<th/>').text(key + ": " + values.length));
});
for (var i = 0; i < cols; i++) {
bodyString += '<tr>';
$.each(obj, function(key, values) {
bodyString += '<td>' +
(values[i] ? values[i] : "") +
'</td>';
});
bodyString += '</tr>';
}
$('.fruitsclass thead').html($header);
$('.fruitsclass tbody').html(bodyString);
var bodyString = '';
var headString = '';
$.each(obj2[key3], function(index) {
bodyString += ('<tr><td>' + obj2[key3][index] + '</td></tr>');
});
headString += ('<tr><th>' + 'Random Fruits' + '</th></tr>');
$('.fruityclass tbody').html(bodyString);
$('.fruityclass thead').html(headString);
$(document).ready(function() {
$("#fruityid td").click(function() {
getval(this);
});
});
function getval(cel) {
alert(cel.innerHTML);
}
.class {
font-family: Open Sans;
}
.center {
display: flex;
justify-content: center
}
.skillsTable th {
border-left: 1px solid #AAA5A4;
border-right: 1px solid #AAA5A4;
}
table {
float: left;
border-collapse: collapse;
width: 70%
}
td {
border-left: 1px solid #AAA5A4;
border-right: 1px solid #AAA5A4;
padding-top: 8px;
padding-left: 11px;
font-size: 15px;
}
th {
color: #0080ff;
font-weight: normal;
border-bottom: 1px solid #AAA5A4;
padding-bottom: 5px;
}
div {
margin-bottom: 50px;
}
<!DOCTYPE html>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<html>
<head>
<meta charset="utf-8" />
<link rel="shortcut icon" href="//#" />
</head>
<body>
<div id="result"> </div>
<div class="center">
<table id="fruitsid" class="fruitsclass skillsTable class">
<thead></thead>
<tbody></tbody>
</table>
</div>
<div class="center">
<table id="fruityid" class="fruityclass skillsTable class">
<thead></thead>
<tbody></tbody>
</table>
</div>
</body>
</html>
Working on top of your code, changed listener function to remove the node:
function listener(obj) {
tbl = document.getElementById("fruitsTable");
if (tbl != null) {
for (var i = 0; i < tbl.rows.length; i++) {
for (var j = 0; j < tbl.rows[i].cells.length; j++)
tbl.rows[i].cells[j].onclick = function () {
getval(this);
data = this.innerHTML;
k1 = Object.keys(obj).find(k => obj[k].indexOf(data) >= 0 )
if (k1 != 'Random Fruits') {
key = 'Random Fruits'
} else {
key = 'Red Fruits';
}
index = obj[k1].indexOf(data);
obj[k1].splice(index, 1);
obj[key].push(data);
redraw(obj);
listener(obj);
};
}
}
}
It finds the relevant key and removes the element from that array, and pushes that into k2. Once done, it redraws the UI.
Fiddle - https://jsfiddle.net/wqzsn7ou/
Related
I am trying to create two tables and populate them with two randomized arrays. I don't remember how I got to this point but below is a codepen I have. I want to create a table class="side" and a table class="top" and put the random arrays in them. Please forgive me for the messy codes. I have no experience with coding and just want to make something for my students. Thank you.
edit1: cut the codes a little. I want to make a table with 3 cells in a column and another table with 4 cells in a row and randomly populate them with the two emojis array respectively. Can anyone help me with the JS codes?
<table class="top">
1
1
1
</table>
<table class="side">
2222
</table>
UPDATE:
Thanks to everyone for your input and advice. With the examples I was able to understand what my codes was lacking. I've posted it below for viewing and have hide the incomplete codes.
const animals = [
"🐕",
"🐈",
"🐄",
"🐐",
"🐎",
"🐖",
"🐇",
"🦆",
"🐔",
"🐁",
"🐑"
];
const fruits = [
"🍇",
"🍊",
"🍑",
"🥝",
"🍈",
"🍉",
"🥭",
"🍎",
"🍓",
"🍆",
"🥕",
"🥒",
"🫑",
"🧅",
"🍄"
];
function shuffle(a) {
let j, x, i;
for (i = a.length - 1; i > 0; i--) {
j = Math.floor(Math.random() * (i + 1));
x = a[i];
a[i] = a[j];
a[j] = x;
}
return a;
}
shuffle(animals);
let t1side = document.getElementsByClassName("tside").item(0);
for (let x = 0; x < 3; x++) {
let tr = document.createElement("tr");
for (let y = 0; y < 1; y++) {
let td = document.createElement("td");
{
td.setAttribute("id", "r" + (x + 1) + "d" + (y + 1));
td.appendChild(document.createTextNode(animals[x * 1 + y]));
}
tr.appendChild(td);
}
t1side.appendChild(tr);
}
shuffle(fruits);
let t2top = document.getElementsByClassName("ttop").item(0);
for (let x = 0; x < 1; x++) {
let tr = document.createElement("tr");
for (let y = 0; y < 4; y++) {
let td = document.createElement("td");
{
td.setAttribute("id", "r" + (x + 1) + "d" + (y + 1));
td.appendChild(document.createTextNode(fruits[x * 1 + y]));
}
tr.appendChild(td);
}
t2top.appendChild(tr);
}
* {
padding: 0;
margin: 0;
}
.top {
top: 0px;
left: 200px;
position: absolute;
}
.side {
top: 100px;
left: 0px;
position: absolute;
}
table.ttop ,table.ttop tr,table.ttop td {
height: 50px;
width: 100px;
padding: 0px;
marging: 0px;
background-color: pink;
font-size: 50px;
text-align: center;
border-collapse: collapse;
border: 0px solid none;
}
table.tside, table.tside tr, table.tside td {
height: 50px;
width: 50px;
padding: 0px;
marging: 0px;
background-color: yellow;
font-size: 80px;
text-align: center;
border-collapse: collapse;
border: 0px solid none;
}
<body>
<style>
</style>
<body>
<div class="top">
<table class="ttop">
</table>
</div>
<div class="side">
<table class="tside">
</table>
</div>
</body>
<script>
</script>
</body>
var spaces2 = [
"🐕",
"🐇",
"🦆",
"🐔",
"🐁",
"🐑"
];
var spaces = [
"🍇",
"🍊",
"🍑",
"🥝",
"🍈",
"🍉",
"🥭",
"🍎",
];
function shuffle(a) {
var j, x, i;
for (i = a.length - 1; i > 0; i--) {
j = Math.floor(Math.random() * (i + 1));
x = a[i];
a[i] = a[j];
a[j] = x;
}
return a;
}
shuffle(spaces2);
var tbody = document.getElementsByTagName("tbody").item(0);
for (var x = 0; x < 3; x++) {
var tr = document.createElement("tr");
for (var y = 0; y < 1; y++) {
var td = document.createElement("td");
{
td.setAttribute("id", "r" + (x + 1) + "d" + (y + 1));
td.appendChild(document.createTextNode(spaces2[x * 1 + y]));
}
tr.appendChild(td);
}
tbody.appendChild(tr);
}
shuffle(spaces);
var top = document.getElementsByClassName("top").item(0);
for (var x = 0; x < 1; x++) {
var tr = document.createElement("tr");
for (var y = 0; y < 4; y++) {
var td = document.createElement("td");
{
td.setAttribute("id", "r" + (x + 1) + "d" + (y + 1));
td.appendChild(document.createTextNode(spaces[x * 1 + y]));
}
tr.appendChild(td);
}
tbody.appendChild(tr);
}
* {
padding: 0;
margin: 0;
}
table.top tbody, tr, td {
height: 50px;
width: 50px;
padding: 0px;
marging: 0px;
background-color: none;
font-size: 40px;
text-align: center;
border-collapse: collapse;
border: 0px solid none;
}
table.side tbody, tr, td {
height: 50px;
width: 50px;
padding: 0px;
marging: 0px;
background-color: none;
font-size: 40px;
text-align: center;
border-collapse: collapse;
border: 0px solid none;
}
<body>
<style>
</style>
<body>
<div class="top">
<table id="top">
</table>
<div class="side">
<table id="side">
<tbody></tbody>
</table>
</div>
</body>
<script>
</script>
</body>
You want to generate tables from javaScript using an aYrray as content. Here is a small snippet of the generation of a table.
const spaces = [
"🍇",
"🍊",
"🍑",
"🥝",
"🍈",
"🍉",
"🥭",
"🍎",
"🍓",
"🍆",
"🥕",
"🥒",
"🫑",
"🧅",
"🍄"
];
function loadEvents() {
generateTable(spaces, "container", ["class1", "class2", "class3", "etc"]);
}
function generateTable(dataTable, containerId, classes) {
shuffle(dataTable);
let container = document.getElementById(containerId);
let table = document.createElement("table");
// Add classes to table
for (const clazz of classes) {
table.classList.add(clazz);
}
// Calculate cant of rows and columns
let cantDataRow = 0;
let cantDataCol = 0;
do {
cantDataRow++;
cantDataCol = Math.ceil(dataTable.length / cantDataRow);
} while (dataTable.length / Math.pow(cantDataRow, 2) > 1);
let aux = 0;
for (let i = 0; i < cantDataRow; i++) { // rows
let row = document.createElement("tr");
for (let j = 0; j < cantDataCol; j++) { // columns
let col = document.createElement("td");
col.textContent = dataTable[aux++];
row.appendChild(col); // Add column to row
}
table.appendChild(row); // Add row to table
}
container.appendChild(table); // Add table to container
}
function shuffle(array) {
for (let i = array.length - 1; i > 0; i--) {
const j = Math.floor(Math.random() * (i + 1));
[array[i], array[j]] = [array[j], array[i]];
}
}
addEventListener("DOMContentLoaded", loadEvents);
table, tr, td{
border: 1px solid black;
border-collapse: collapse;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="style.css">
<title>Document</title>
</head>
<body>
<div id="container"></div>
<script src="script.js"></script>
</body>
</html>
You would only have to call the function passing it the array with the data of the table, the container of the table and the classes that you want it to contain.
It is not necessary to create the shuffle function twice. It is created only once and can be called infinitely many times. I recommend using let instead of var.
Nice question :-) You only need one loop for each table. I did it with a for loop. I added a function that outputs a random image.
const t1 = document.querySelector('.top');
const t2 = document.querySelector('.side');
const spaces2 = [
"🐕",
"🐇",
"🦆",
"🐔",
"🐁",
"🐑"
];
const spaces = [
"🍇",
"🍊",
"🍑",
"🥝",
"🍈",
"🍉",
"🥭",
"🍎",
];
let tr = document.createElement('tr');
for (let i = 0; i < 3; i++) {
let td = document.createElement('td');
td.innerHTML = getRandomElement(spaces2);
tr.append(td);
}
t1.append(tr);
// t2
for (let i = 0; i < 4; i++) {
let tr = document.createElement('tr');
let td = document.createElement('td');
td.innerHTML = getRandomElement(spaces);
tr.append(td);
t2.append(tr);
}
function getRandomElement(items) {
return items[Math.floor(Math.random()*items.length)];
}
small {
font-size: 16px;
padding-left:5px;
}
table {
}
table td {
border: 2px solid #999;
padding: 5px;
}
<h2>Table 1<small>3 cols and 1 row</small></h2>
<table class="top"></table>
<h2>Table 2<small>1 cols with 4 rows</small></h2>
<table class="side"></table>
I am Michael and I am new to this forum.
What I want to ask is how through Java Script to make a character 'O' follow your character 'X' in a '.' that is a 20*20 array, but where 'X' pass '.' is replaced with 'O'.
E.g. increase some way the counters inside the if statement that relies in the for loops of row and column of "array a" ?
function start()
{
document.getElementById("wrapper").style="visibility:hidden";
var optionOne = document.getElementById("optionOne");
var display = "";
var txt1 = document.getElementById("txt1");
var mtxt1 = parseInt(txt1.value);
if (mtxt1 == 1)
{
display += "<p>Pen is currently NOT DRAWING</p>";
document.getElementById("wrapper").style="visibility:display";
}
else if (mtxt1 == 2)
{
display += "<p>Pen is DRAWING</p>";
document.getElementById("wrapper").style="visibility:display";
}
optionOne.innerHTML = display;
var button = document.getElementById("getbutton");
button.addEventListener("click",start,false );
//var displaygmb = document.getElementById("displaygmb");
//displaygmb.addEventListener("click", displaygameboard("Gameboard",array,length,arraydisplay),false );
var button2 = document.getElementById("get2button");
button2.addEventListener("click",option2(button2,mtxt1),false );
}
function option2(buttonn,symbolinput)
{
var input = symbolinput;
var usedspace = "O";
var turtle = "X";
var gameboardSymbol = ".";
var clickcountt = buttonn;
var count6 = 1;
var count5 = 1;
var count3 = 1;
var count4 = 1;
var display = "";
clickcountt.onclick = function() {
var optiontwo = document.getElementById("optiontwo");
var display2 = "";
var txt2 = document.getElementById("txt2");
var mtxt2 = parseInt(txt2.value);
if (mtxt2 == 6)
{
count6 += 1;
display2 += "<p>Turtle is moving "+count6+" places down</p>";
}
else if (mtxt2 == 5)
{
count6 -=1;
count5 +=1;
display2 += "<p>Turtle is moving "+count6+" places up</p>";
}
else if (mtxt2 == 3)
{
count3 += 1;
display2 += "<p>Turtle is moving "+count3+" places to the right</p>";
}
else if (mtxt2 == 4)
{
count3 -=1
count4 += 1;
display2 += "<p>Turtle is moving "+count3+" places to the left</p>";
}
optiontwo.innerHTML = display2;
var gameboardsize = 20;
var arraydisplay = document.getElementById("arraydisplay");
var array = new Array (gameboardsize);
var length = array.length;
for (var i = 0; i <= length; i++ )
{
array[i] = new Array(gameboardsize);
}
var arraydisplay = document.getElementById("arraydisplay");
var displaygbd = "<table id=gameb align=center><thead><th>"+"Gameboard"+"</th></thead><tbody>";
for (var row = 1; row <= length; row++)
{
//three += 1;
displaygbd += "<tr>";
for (var col = 1; col <= length; col++)
{
if (input == 1){
//four += 1;
if (((row ==count6)&&(col ==count3)))
{
array[row][col]= turtle;
}
else {
array[row][col]=gameboardSymbol;
}
}
//----------------------------
else if(input == 2)
{
if (((row == count6)&&(col ==count3)))
{
array[row][col]= turtle;
}
/*how to make 'O' follow 'X' by ibncrease the appropriate counter in the if below?*/
else if (((row <= count6)&&(col <=count3)))
{
array[row][col]= usedspace;
}
else if ((((row >= count6)||(col >= count3))))
{
array[row][col]=gameboardSymbol;
}
}//end else if
//----------------------------
displaygbd += "<th>"+array[row][col]+"\xa0"+"</th>";
}
displaygbd += "</tr>";
}
displaygbd += "</tbody></table>";
arraydisplay.innerHTML = displaygbd;
}//end clickout function
}
window.addEventListener("load",start,false);
#charset "ISO-8859-1";
#customers {
font-family: "Trebuchet MS", Arial, Helvetica, sans-serif;
border-collapse: collapse;
width: 30%;
}
#customers td, #customers th {
border: 1px solid #ddd;
padding: 8px;
}
#customers thead th {
padding-top: 12px;
padding-bottom: 12px;
text-align: center;
background-color: #4CAF50;
color: white;
}
#customers tbody th {
padding-top: 12px;
padding-bottom: 12px;
text-align: left;
background-color: white;
color: black;
text-align:center;
}
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Initializing an array</title>
<link rel="stylesheet" type="text/css" href="style.css">
<script src ="tutle.js"></script>
</head>
<body>
select your first option
<input id ="txt1" type="text">
<input id = "getbutton" type ="button" value = "your option">
<div id = "optionOne"></div>
<br/>
<div id = "arraydisplay"></div>
<div id="wrapper" >
select your second option
<input id ="txt2" type="text">
<input id = "get2button" type ="button" value = "your option">
<div id = "optiontwo"></div>
</div>
<div id = "counters"></div>
<div id = "optionthree"></div>
</body>
</html>
Sharing a possible solution.
This should get you more than started.
Try running this here itself and let me know if this is ok. I'll add an explanation if required.
The 2 inputs receive the new location of 'X'. text1 receives row number and text2 receives column number. On button press, the corresponding dimension is updated.
var button1 = document.getElementById('getbutton');
var button2 = document.getElementById('get2button');
var textbox1 = document.getElementById('txt1');
var textbox2 = document.getElementById('txt2');
var gridX = 20;//table size length wise
var gridY = 20;//table size width wise
var arrayContainer = document.getElementById('arraydisplay');
var currentX = 1;//initial positions
var currentY = 1;
function init() {
var myTable = document.createElement('table');
myTable.setAttribute("id", "customers");
arrayContainer.appendChild(myTable);
//Creating initial grid
for(var i=0; i<gridX; i++) {
var row = document.createElement('tr');
for(var j=0; j<gridY; j++) {
var text = document.createTextNode('.');
var column = document.createElement('td');
column.appendChild(text);
row.appendChild(column);
}
myTable.appendChild(row);
}
//Setting initial value
document.getElementsByTagName('tr')[currentX-1].getElementsByTagName('td')[currentY-1].innerText = 'X';
}
init();
button1.onclick = clicked;
function clicked() {//1st position changed
var newX = parseInt(textbox1.value);
var newY = parseInt(textbox2.value);
moveTo(newX, newY);
}
button2.onclick = clicked;
function moveTo(newX, newY) {
//Setting old value to 'O'
var char = 'O'
if(newX == 1)
char = '.';
document.getElementsByTagName('tr')[currentX-1].getElementsByTagName('td')[currentY-1].innerText = char;
//Setting new location with 'X'
document.getElementsByTagName('tr')[newX-1].getElementsByTagName('td')[newY-1].innerText = 'X';
//Updating current location of 'X' for future use.
currentX = newX;
currentY = newY;
}
#charset "ISO-8859-1";
#customers {
font-family: "Trebuchet MS", Arial, Helvetica, sans-serif;
border-collapse: collapse;
width: 30%;
}
#customers td, #customers th {
border: 1px solid #ddd;
padding: 8px;
}
#customers thead th {
padding-top: 12px;
padding-bottom: 12px;
text-align: center;
background-color: #4CAF50;
color: white;
}
#customers tbody th {
padding-top: 12px;
padding-bottom: 12px;
text-align: left;
background-color: white;
color: black;
text-align:center;
}
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Initializing an array</title>
<link rel="stylesheet" type="text/css" href="style.css">
<!-- <script src ="turtle.js"></script> -->
</head>
<body>
select your first option
<input id ="txt1" type="text">
<input id = "getbutton" type ="button" value = "your option">
<div id = "optionOne"></div>
<div id="wrapper" >
select your second option
<input id ="txt2" type="text">
<input id = "get2button" type ="button" value = "your option">
<div id = "optiontwo"></div>
</div>
<div id = "counters"></div>
<div id = "optionthree"></div>
<br>
<div id = "arraydisplay"></div>
</body>
<script src ="turtle.js"></script>
</html>
Im beginner. I use a HTML table code like this (see below) for Unicode print using char's Decimal values:
<table border="1">
<tr><td>1</td><td></td>
<tr><td>2</td><td></td>
<tr><td>3</td><td></td>
...
<!-- last one: thousandth row -->
<tr><td>1000</td><td>Ϩ</td>
</table>
Is it possible to convert this code into an auto-generated table as follows using JavaScript or JQuery?
<table border="1">
<tr><td>rowNumber</td><td>innerHTML = "\u0026\u0023 + rowNumber + \u003B";</td>
...
<!-- thousandth row -->
<tr><td>rowNumber</td><td>innerHTML = "\u0026\u0023 + rowNumber + \u003B";</td>
</table>
You can start by creating a record-generating function.
function generateRecords(recordFn, limit) {
var records = [];
for (var i = 0; i < limit; i++) {
records.push(recordFn.call(null, i, records));
}
return records;
}
Then you can generate the JSON.
generateRecords(i => {
return {
dec: i,
entity: '&#' + i + ';',
rendered: '&#' + i + ';'
}
}, 1000);
Finally, all you need to do is render the JSON to a table.
Example
(function($) {
$.fn.attrs = function(attrs) {
var $self = this;
if (attrs != null) {
$.each(attrs, function(attr, value) {
$self.attr(attr, value);
});
return $self;
} else {
var result = {};
$.each(this[0].attributes, function(index, attribute) {
result[attribute.name] = attribute.value;
});
return result;
}
};
$.fn.tableFromJson = function(data, attrs, indexField) {
return this.replaceWith($.tableFromJson.apply(this, arguments));
};
$.tableFromJson = function(data, attrs, indexField) {
var fields = Object.keys(data[0]);
if (indexField != null) fields.unshift(indexField);
return $('<table>')
.append($('<thead>').append($('<tr>').append(fields
.map(field => $('<th>').text(field)))))
.append($('<tbody>').append(data
.map((rec, row) => $('<tr>').append(fields
.map((field, col) => $('<td>').html(field === indexField ? (row + 1) : rec[field])))))).attrs(attrs);
};
})(jQuery);
function generateRecords(recordFn, limit) {
var records = [];
for (var i = 0; i < limit; i++) {
records.push(recordFn.call(null, i, records));
}
return records;
}
$('.column:nth-child(1) .result').tableFromJson(generateRecords(i => {
return {
dec: i,
entity: '&#' + i + ';',
rendered: '&#' + i + ';'
}
}, 1000), $('.column:nth-child(1) .result').attrs());
$('.column:nth-child(2) .result').tableFromJson(generateRecords(i => {
return {
dec: i,
rendered: '\u0026\u0023' + i + '\u003B'
}
}, 1000), $('.column:nth-child(2) .result').attrs());
.container { width: 100%; }
.column { display: inline-block; width: 49%; }
table.result {
margin-bottom: 0.5em;
}
table.result,
table.result th,
table.result td {
border: 1px solid black;
border-collapse: collapse;
}
table.result th,
table.result td {
padding: 0.25em;
}
table.result tbody tr td {
text-align: center;
}
table.result thead tr {
background: #BBB;
}
table.result tbody tr:nth-child(even) {
background: #EEE;
}
table.result tbody tr:nth-child(odd) {
background: #FFF;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="container">
<div class="column">
<table class="result"></table>
</div>
<div class="column">
<table class="result"></table>
</div>
</div>
You can try with this
var table = $('<table>').prop('border', 1);
for(i=0; i<1000; i++){
var row = $('<tr><td>' + i + '</td><td>&#'++'</td></tr>'
table.append(row);
}
$('#mytable').append(table);
Yes, Thats possible using javascript/JQuery.For that you need to use proper js code. Below is the sample code that can help you to create table and row,data using jquery.
Below code is responsible to create table tag
$('.class-name').append('<table border="3"></table>');
This will create table element inside your HTML having classname as .class-name.
Once the table tag is created you can create table row and data element as below.
$("table").append(createRow());
function createRow(){
var firstVal = '1st val';
var secondVal = '2nd val';
var tr = '<tr>' ;
tr += '<td>' + firstVal + '</td>';
tr += '<td>' + secondVal + '</td>';
tr +='</tr>';
return tr;
}
This code will generate the table row and will print the table data as st val and 2nd val.
Hope this code may help you
I have this code below that popups the cell value whenever the user clicks a specific cell.
What I'm currently trying to do is when the user clicks a cell i want that cell value to be appended to another column. I tried using the push method but it doesn't seem to be working. I'm not sure if I'm doing it the wrong way
JFiddle
HTML:
<table id="fruitsTable" class="fruitstableroni skillsTable class">
<thead></thead>
<tbody></tbody>
</table>
JavaScript:
var tbl = document.getElementById("fruitsTable");
if (tbl != null) {
for (var i = 0; i < tbl.rows.length; i++) {
for (var j = 0; j < tbl.rows[i].cells.length; j++)
tbl.rows[i].cells[j].onclick = function () {
obj[key2].push(this); //Trying to push it to the second column.
console.log(this);
};
}
}
function getval(cel) {
//console.log(cel.innerHTML);
}
var obj = {};
var key = "Red Fruits";
obj[key] = ['Apple', 'Cherry', 'Strawberry'];
var myArray = [];
myArray.push(obj);
var key2 = "Green Fruits";
obj[key2] = ['Watermelon', 'Durian', 'Avacado'];
var myArray2 = [];
myArray2.push(obj);
var key3 = "Random Fruits";
obj[key3] = ['Soursop', 'Papaya', 'Pineapple', 'Melon'];
var myArray3 = [];
myArray3.push(obj);
var $header = $("<tr>"),
cols = 0,
bodyString = "";
$.each(obj, function(key, values) {
cols = Math.max(cols, values.length); // find the longest
$header.append($('<th/>').text(key + ": " + values.length));
});
for (var i = 0; i < cols; i++) { // or use .map, but this is more undertandable for beginners
bodyString += '<tr>';
$.each(obj, function(key, values) {
bodyString += '<td>' +
(values[i] ? values[i] : "") + // ternary - instead of using if/else
'</td>';
});
bodyString += '</tr>';
}
$('.fruitsTableClass thead').html($header);
$('.fruitsTableClass tbody').html(bodyString);
var tbl = document.getElementById("fruitsTable");
if (tbl != null) {
for (var i = 0; i < tbl.rows.length; i++) {
for (var j = 0; j < tbl.rows[i].cells.length; j++)
tbl.rows[i].cells[j].onclick = function() {
getval(this);
obj[key2].push(this);
};
}
}
function getval(cel) {
alert(cel.innerHTML);
}
.class {
font-family: Open Sans;
}
.center {
display: flex;
justify-content: center
}
.skillsTable th {
border-left: 1px solid #AAA5A4;
border-right: 1px solid #AAA5A4;
}
table {
float: left;
border-collapse: collapse;
width: 70%
}
td {
border-left: 1px solid #AAA5A4;
border-right: 1px solid #AAA5A4;
padding-top: 8px;
padding-left: 11px;
font-size: 15px;
}
th {
color: #0080ff;
font-weight: normal;
border-bottom: 1px solid #AAA5A4;
padding-bottom: 5px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="center">
<table id="fruitsTable" class="fruitsTableClass skillsTable class">
<thead></thead>
<tbody></tbody>
</table>
</div>
Restructure your code to have a method to redraw UI and to enable event listeners:
function redraw (obj) {
var $header = $('<tr>'),
cols = 0,
bodyString = ''
$.each(obj, function (key, values) {
cols = Math.max(cols, values.length) // find the longest
$header.append($('<th/>').text(key + ': ' + values.length))
})
for (var i = 0; i < cols; i++) { // or use .map, but this is more undertandable for beginners
bodyString += '<tr>'
$.each(obj, function (key, values) {
bodyString += '<td>' +
(values[i] ? values[i] : '') + // ternary - instead of using if/else
'</td>'
})
bodyString += '</tr>'
}
$('.fruitsTableClass thead').html($header)
$('.fruitsTableClass tbody').html(bodyString)
}
function listener (obj) {
tbl = document.getElementById('fruitsTable')
if (tbl != null) {
for (var i = 0; i < tbl.rows.length; i++) {
for (var j = 0; j < tbl.rows[i].cells.length; j++)
tbl.rows[i].cells[j].onclick = function () {
getval(this)
obj[key2].push(this.innerHTML)
redraw(obj)
listener(obj)
};
}
}
}
function getval (cel) {
alert(cel.innerHTML)
}
redraw(obj)
listener(obj)
JSFiddle - https://jsfiddle.net/gnm8wv5f/
To add rows or cells to a table, you should use the methods insertRow() and insertCell().
Example, if you want to add a cell at the beginning of a row (from w3schools):
var row = document.getElementById("myRow");
var x = row.insertCell(0);
x.innerHTML = "New cell";
Or, to insert at the end:
var x = row.insertCell(row.cells.length);
Using cells.length you can find the number of cells in a particluar row, in that way you could know where to insert the new cell.
More info in: w3 | MDN
Try this code.
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
var daraArray=[];
$(document).ready(function(){
$(".classTd").click(function(){
//console.log($(this).html());
daraArray.push($(this).html());
console.log(daraArray);
});
});
</script>
<style type="text/css">
.classTd{
text-align: center;
}
</style>
</head>
<table id="fruitsTable" class="fruitstableroni skillsTable class" border="1">
<thead></thead>
<tbody>
<tr>
<td class="classTd" width="10%">1</td>
<td class="classTd" width="10%">2</td>
<td class="classTd" width="10%">3</td>
</tr>
<tr>
<td class="classTd" width="10%">4</td>
<td class="classTd" width="10%">5</td>
<td class="classTd" width="10%">6</td>
</tr>
<tr>
<td class="classTd" width="10%">7</td>
<td class="classTd" width="10%">8</td>
<td class="classTd" width="10%">9</td>
</tr>
</tbody>
</table>
</html>
The other answers here are good but you should definitely try AngularJs. The ng-repeat tag will easily cater your functionality.
I am trying to append / (Bind) textbox innerhtml value to the dynamic div which has the pagination. When I am trying append with textbox with the div I am getting an error.
There are two elements in my initial page First One is for no of pages and other one is for enter some text. If I enter number 2 so two div will appear dynamically. Then I enter the greeting text second text box. Text should appear in the first div and for the second div if i click the button in the bottom second div should be empty. Using Pure javascript (Vanila).
I am trying to get value from the textbox. But I was not able to bind with the p tag which was available dynamically.
Kindly help me.
var gettext_Title = document.getElementById('title_Text')
var getresult = gettext_Title.value;
//alert(result);
var inputElement = document.getElementById("inputAdd_page");
var totalCount = 0;
inputElement.addEventListener('blur', function() {
var count = this.value;
// Gaurd condition
// Only if it is a number
if (count && !isNaN(count)) {
fragment = document.createDocumentFragment();
for (var j = 0; j < count; ++j) {
spancount = document.createElement('span');
prevPage = document.createElement('div');
navbutton = document.createElement('button');
hTitle = document.createElement('p');
preview_PageSize = document.getElementById('page');
navpageBtn = document.getElementById('pageBtn');
navbutton.className = "div_navig";
navbutton.setAttribute('id', ['pag_navg' + totalCount]);
navbutton.setAttribute('data-page', totalCount);
navbutton.innerHTML = [1 + totalCount];
navbutton.addEventListener('click', function (e) {
var el = e.target;
var page = parseInt(el.getAttribute('data-page'), 10);
var allPages = document.querySelectorAll('.preview_windowSize_element');
Array.prototype.forEach.call(allPages, function (pageElement) {
pageElement.style.zIndex = 0;
});
var pageEl = document.querySelector('div[data-page="' + page + '"]');
pageEl.style.zIndex = 10;
});
spancount.className = "spanCount";
spancount.innerHTML = [1 + totalCount];
hTitle.setAttribute('id', ['Title' + (totalCount)]);
hTitle.className = "title_boundry";
prevPage.className = "preview_windowSize_element";
prevPage.setAttribute('id', ['page' + (totalCount)]);
prevPage.setAttribute('data-page', totalCount);
prevPage.appendChild(spancount);
prevPage.appendChild(hTitle);
navpageBtn.appendChild(navbutton);
preview_PageSize.insertBefore(prevPage, preview_PageSize.childNodes[0]);
totalCount++;
}
inputElement.value = "";
document.body.appendChild(fragment);
}
});
Here is the Jsfiddle Link
Thanks in advance
Kindly help me
Cheers,
If I understand correctly what you mean, try this:
main.js :
(function () {
var inputTitle,
inputElement,
current,
totalCount = 0;
document.addEventListener('DOMContentLoaded', function (e) {
inputTitle = document.getElementById('title_Text');
inputElement = document.getElementById("inputAdd_page");
inputElement.addEventListener('blur', onInputElementBlur);
inputTitle.addEventListener('blur', onInputTitleBlur);
});
function onInputTitleBlur(e) {
if (!!current) {
var title = current.querySelector('p');
title.innerText = inputTitle.value;
inputTitle.value = '';
}
}
function onInputElementBlur() {
var count = this.value;
// Gaurd condition
// Only if it is a number
if (count && !isNaN(count)) {
var fragment = document.createDocumentFragment();
for (var j = 0; j < count; ++j) {
var spancount = document.createElement('span');
var prevPage = document.createElement('div');
var navbutton = document.createElement('button');
var hTitle = document.createElement('p');
var preview_PageSize = document.getElementById('page');
var navpageBtn = document.getElementById('pageBtn');
navbutton.className = "div_navig";
navbutton.setAttribute('id', 'pag_navg' + totalCount);
navbutton.setAttribute('data-page', totalCount);
navbutton.innerHTML = 1 + totalCount;
navbutton.addEventListener('click', function (e) {
var el = e.target;
var page = parseInt(el.getAttribute('data-page'), 10);
var allPages = document.querySelectorAll('.preview_windowSize_element');
Array.prototype.forEach.call(allPages, function (pageElement) {
pageElement.style.zIndex = 0;
});
var pageEl = document.querySelector('div[data-page="' + page + '"]');
current = pageEl;
pageEl.style.zIndex = 10;
});
spancount.className = "spanCount";
spancount.innerHTML = 1 + totalCount;
hTitle.setAttribute('id', 'Title' + (totalCount));
hTitle.className = "title_boundry";
prevPage.className = "preview_windowSize_element";
prevPage.setAttribute('id', 'page' + (totalCount));
prevPage.setAttribute('data-page', totalCount);
prevPage.appendChild(spancount);
prevPage.appendChild(hTitle);
navpageBtn.appendChild(navbutton);
preview_PageSize.insertBefore(prevPage, preview_PageSize.childNodes[0]);
totalCount++;
}
current = document.querySelector('div[data-page="0"]');
inputElement.value = "";
document.body.appendChild(fragment);
}
}
}());
index.html :
<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8">
<title></title>
<link id="myStyleSheet" href="style.css" rel="stylesheet" type="text/css">
</head>
<body>
<input type="text" class="form-control title_Textbox" id="title_Text" placeholder="Text">
<input type="text" class="form-control title_Textbox" id="inputAdd_page" placeholder="No Of Pages">
<div class="preview_windowSize" id="page"></div>
<div id="pageBtn" class="row pagination_btn"></div>
<script src="main.js" type="text/javascript"></script>
</body>
</html>
style.css :
.div_navig {
background: lightGrey;
width: 24px;
height: 24px;
text-align: center;
margin-left: 5px;
color: black;
cursor: pointer;
}
.pagination_btn {
float: right;
margin: 0 20px 0 0;
padding-left: 5px;
}
.spanCount {
position: absolute;
bottom: 0;
right: 0;
padding: 0 10px 0 5px;
}
.preview_windowSize {
margin: 15px 15px 15px 15px;
height: 300px;
padding: 5px;
}
.preview_windowSize_element {
position: absolute;
background-color: lightGrey;
border: 1px solid rgb(155, 155, 155);
border-bottom-right-radius: 10px;
border-bottom-left-radius: 10px;
padding: 5px;
width: 93.5%;
height: 300px;
}
.title_boundry {
border: 1px dotted #000;
height: 40px;
}