Create a table from an object jquery/javascript - javascript

I am trying to implement the following.
A user enters a sentence into a textbox following which a table is created. An example would be this.
Input: "This is what I want to achieve"
Result:
Currently, based on the code I have there is an object that looks like this:
{t: ["this", "to"], i: ["is", "i"], w: ["what", "want"], a: ["achieve"]};
Below is the current code I have (also see jsfiddle here).
I am able to take the input string and create a table with a row which has the first letter of each word.
HTML
<textarea id="text-input" name="textarea" rows="5" cols="25">This is what I want to achieve</textarea>
<button class="calculate">Calculate</button>
<table>
<tbody>
<tr class="words-header"></tr>
</tbody>
</table>
Javascript
$(document).ready(function() {
$(".calculate").click(function() {
var result = {},
arr = [];
var array = $("#text-input").val().toLowerCase().split(" ");
for (var i = 0; i < array.length; i++) {
if (typeof result[array[i][0]] == 'undefined') {
result[array[i][0]] = [];
}
result[array[i][0]].push(arr[i]);
}
for (var key in result) {
$(".words-header").append("<td>" + key.toUpperCase() + "</td>");
}
});
});
I believe the final table should look like this if it helps:
<table>
<tr>
<td>A</td>
<td>I</td>
<td>T</td>
<td>W</td>
</tr>
<tr>
<td>achieve</td>
<td>is</td>
<td>this</td>
<td>what</td>
</tr>
<tr>
<td> </td>
<td>i</td>
<td>to</td>
<td>want</td>
</tr>
</table>

You can do it this way (Try it by clicking the Run code snippet button below):
var app = app || {};
(function() {
"use strict";
var result, arr;
app.initialize = {
init: function() {
app.splitWords.init();
}
};
app.splitWords = {
init: function() {
$(".calculate").click(function() {
result = [];
arr = $("#text-input").val().split(" ");
app.createMultiArray.init(arr);
});
}
};
app.createMultiArray = {
init: function(array) {
for (var i = 0; i < array.length; i++) {
var letter = array[i][0].toLowerCase();
if (typeof result[letter] == 'undefined') {
result[letter] = [];
}
result[letter].push(array[i]);
}
// I added this method
app.buildTable.init(result);
}
};
app.buildTable = {
init: function(result) {
var headers = Object.keys(result),
max_rows = 0,
rows_html = '';
headers.sort();
app.createHeaders.init(headers);
// Determine how many rows you'll need
for (var i = 0; i < headers.length; i++) {
if(result[headers[i]].length > max_rows) { max_rows = result[headers[i]].length; }
}
// Loop "max_rows" times
for (var i = 0; i < max_rows; i++) {
rows_html += '<tr>';
// Loop through all letters
for(var j = 0; j < headers.length; j++) {
rows_html += '<td>';
if(i < result[headers[j]].length) {
rows_html += result[headers[j]][i];
}
rows_html += '</td>';
}
rows_html += '</tr>';
}
$(".words-header").after(rows_html);
}
};
app.createHeaders = {
init: function(headers) {
// Empty the table in case of multiple tries
$(".words-header").parent().html('<tr class="words-header"></tr>');
for (var i = 0; i < headers.length; i++) {
$(".words-header").append("<td>" + headers[i].toUpperCase() + "</td>");
}
}
};
app.docOnReady = {
init: function() {
app.initialize.init();
}
};
$(document).ready(app.docOnReady.init);
})(jQuery);
#results-table table{ border-collapse: collapse; } #results-table td{ border: 1px solid #000; padding: .2em;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<textarea id="text-input" name="textarea" rows="5" cols="25">This is what I want to achieve</textarea>
<button class="calculate">Calculate</button>
<div id="results-table">
<table>
<tbody>
<tr class="words-header"></tr>
</tbody>
</table>
</div>

Related

Get html table row and cell index with javascript function

I neet to return row and cell index according to user click in table.
My function:
function updatePrice()
{
var rIndex, cellIndex, table = document.getElementsByTagName('table')[0];
for(var i = 0; i < table.rows.length; i++){
table.rows[i].onclick = function valorLinha() {
rIndex = this.rowIndex;
/*console.log here works fine*/
};
for (var j = 0; j < table.rows[i].cells.length; j++)
table.rows[i].cells[j].onclick = function () {
cellIndex = this.cellIndex;
};
/*I NEED values of rIndex and cellIndex here*/
console.log(rIndex);
console.log(cellIndex);
}
}
I'm getting undefined when console.log runs.
How can I solve this?
var table = document.getElementsByTagName('table')[0];
for (let i = 0; i < table.rows.length; i++) {
for (let j = 0; j < table.rows[i].cells.length; j++){
table.rows[i].cells[j].onclick = function(){
console.log("Row = "+i+" Cell = "+j)
}
}
}
rIndex is the same as i variable in the loop
and cellIndex is a collection you should loop it
function updatePrice()
{
var rIndex, cellIndex, table = document.getElementsByTagName('table')[0];
for(var i = 0; i < table.rows.length; i++){
var rowi = table.rows[i];
// rIndex = rowi.rowIndex = i;
rIndex = i;
console.log(rIndex);
// cellIndex are multiple, you should loop
for (var j = 0; j < rowi.cells.length; j++){
var cellj = rowi.cells[j];
cellIndex = cellj.cellIndex;console.log(cellIndex);
}
}
}```
document.querySelectorAll('#table td')
.forEach(e => e.addEventListener("click", function() {
// Here, `this` refers to the element the event was hooked on
console.log("clicked cell at: " + this.cellIndex + ", " + this.parentNode.rowIndex);
}));
td{
cursor:pointer;
}
<table id="table">
<tbody>
<tr>
<td>00</td>
<td>10</td>
</tr>
<tr>
<td>01</td>
<td>11</td>
</tr>
<tr>
<td>02</td>
<td>12</td>
</tr>
</tbody>
</table>

Append table array value to another array

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.

Bundle of onclick() function, Change with Event listener

In the html below, there are many many onclick() function, which i want to change it to eventlistner. I am new to web Programming, previously working with onlick(), But w3 standards has change to event listener. Any Help is greatly appriciated. i want to change onlick() with event listener.
Html:
<p>
<button onclick="window.location.reload()">New Game</button>
</p>
<table class="boxes" >
<tr>
<td id="0" class="BoxCell" onclick="clickCell(this)">1</td>
<td id="1" class="BoxCell" onclick="clickCell(this)">2</td>
</tr>
<tr>
<td id="2" class="BoxCell" onclick="clickCell(this)">3</td>
<td id="3" class="BoxCell" onclick="clickCell(this)">4</td>
</tr>
<tr>
<td id="4" class="BoxCell" onclick="clickCell(this)">5</td>
<td id="5" class="BoxCell" onclick="clickCell(this)">6</td>
</tr>
<tr>
<td id="6" class="BoxCell" onclick="clickCell(this)">7</td>
<td id="7" class="BoxCell" onclick="clickCell(this)">8</td>
</tr>
</table>
JS :
var id_empty;
var num_moves;
var isCompleted = false;
var nums = [1,2,3,4,5,6,7,8];
function startPuzzle() {
num_moves = 0;
isCompleted = false;
for(var i=0; i < 8; i++) {
var tmp = document.getElementById(i);
tmp.className = "BoxCell ";
}
randomNumber = nums.sort(function () { return (Math.round(Math.random())-0.5);});
while(!Problem.prototype.is_solvable(randomNumber)) {
randomNumber = nums.sort(function () { return (Math.round(Math.random())-0.5);});
}
for(var i=0; i < 8; i++) {
var tmp = document.getElementById(i);
if(randomNumber[i] == 8) {
tmp.className = "cell empty";
tmp.innerHTML = "";
id_empty = i;
}
else
tmp.innerHTML = randomNumber[i];
}
}
function clickCell(x)
{
if(isCompleted)
return;
if(x.id != id_empty+'') {
var emptyI = Math.floor(id_empty/2);
var emptyJ = id_empty % 2;
var id_selected = Number(x.id);
var selectedI = Math.floor(id_selected/2);
var selectedJ = id_selected % 2;
if((Math.abs(emptyI - selectedI) == 1 && emptyJ == selectedJ) ||
(Math.abs(emptyJ - selectedJ) == 1 && emptyI == selectedI)) {
document.getElementById(id_empty).className = "BoxCell";
document.getElementById(id_empty).innerHTML = x.innerHTML;
x.className = "cell empty";
x.innerHTML = '';
id_empty = id_selected;
num_moves++;
document.getElementById("moves").innerHTML = "Moves so far: " + num_moves;
if(isDone()){
isCompleted = true;
document.getElementById("moves").innerHTML = "CONGRATS! Number of moves it took to complete: " + num_moves;
}
}
}
}
function isDone() {
return document.getElementById('0').innerHTML == '1' &&
document.getElementById('1').innerHTML == '2' &&
document.getElementById('2').innerHTML == '3' &&
document.getElementById('3').innerHTML == '4' &&
document.getElementById('4').innerHTML == '5' &&
document.getElementById('5').innerHTML == '6' &&
document.getElementById('6').innerHTML == '7';
}
function lastClick() {
var curr_state = currentState();
var problem = new Problem(curr_state);
var sol = Solver.a_star_search(problem);
var result = "<ol>";
for(var i = 0; i < sol.length; i++) {
var n = moveNumb(sol[i],curr_state);
curr_state = problem.result(sol[i],curr_state);
result += "<li>move " + n + "</li>";
}
result += "</ol>";
document.getElementById("steps").innerHTML = result;
}
function currentState() {
var result = [];
for(var i = 0; i < 8; i++) {
var tmp = document.getElementById(String(i)).innerHTML;
if(tmp == '') {
result[i] = 8;
}
else {
result[i] = Number(tmp);
}
}
return result;
}
function moveNumb(action,state) {
var i = state.indexOf(8);
switch(action) {
case Action.up:
return state[Util.index(Util.x(i),Util.y(i) - 1)];
case Action.down:
return state[Util.index(Util.x(i),Util.y(i) + 1)];
case Action.right:
return state[Util.index(Util.x(i) + 1,Util.y(i))];
case Action.left:
return state[Util.index(Util.x(i) - 1,Util.y(i))];
}
}
Array.prototype.clone = function() { return this.slice(0); };
Array.prototype.swap = function(i1,i2) {
var copy = this.clone();
var tmp = copy[i1];
copy[i1] = copy[i2];
copy[i2] = tmp;
return copy;
};
var Problem = function(start_state) {
this.init_state = start_state;
return this;
}
Problem.prototype.is_solvable = function(start) {
start = start.clone();
start.splice(start.indexOf(8), 1);
start[7] = 8;
var count = 0;
for(var i = 0; i < 7; i++) {
if(start[i] != i+1) {
count++;
var j = start.indexOf(i+1);
start[j] = start[i];
start[i] = i+1;
}
}
return count % 2 == 0;
}
For the cells part you could attach the click event to the class BoxCell like :
var box_cell = document.getElementsByClassName("BoxCell");
var clickCell = function() {
console.log(this.id);
}
for (var i = 0; i < box_cell.length; i++) {
box_cell[i].addEventListener('click', clickCell, false);
}
For the button it could be :
document.querySelector("#btnReload").addEventListener("click", function(){
window.location.reload();
});
Hope this helps.
var box_cell = document.getElementsByClassName("BoxCell");
var clickCell = function() {
console.log(this.id);
};
for (var i = 0; i < box_cell.length; i++) {
box_cell[i].addEventListener('click', clickCell, false);
}
<table class="boxes">
<tr>
<td id="0" class="BoxCell">1</td>
<td id="1" class="BoxCell">2</td>
</tr>
<tr>
<td id="2" class="BoxCell">3</td>
<td id="3" class="BoxCell">4</td>
</tr>
<tr>
<td id="4" class="BoxCell">5</td>
<td id="5" class="BoxCell">6</td>
</tr>
<tr>
<td id="6" class="BoxCell">7</td>
<td id="7" class="BoxCell">8</td>
</tr>
</table>
I haven't gone through your entire code, but you can do like the following:
On window load, you can loop through the td elements and attach click event listeners like: (Also included click event for New Game button - I assigned id - btnReload to the button).
window.onload = function () {
for (i = 0; i <= 7; i++) {
document.getElementById(i).addEventListener("click", function (e) {
clickCell(e);
})
}
document.getElementById("btnReload").addEventListener("click", function(){
window.location.reload();
})
}
Your clickCell can be changed like this:
function clickCell(e) {
var x = e.target.id;
console.log(x);
//reset of your code
}
Example:
window.onload = function () {
for (i = 0; i <= 7; i++) {
document.getElementById(i).addEventListener("click", function (e) {
clickCell(e);
})
}
document.getElementById("btnReload").addEventListener("click", function(){
window.location.reload();
})
}
function clickCell(e) {
var x = e.target.id;
console.log(x);
//reset of your code
}
<h2>Puzzle Game</h2>
<p id="moves"></p>
<p>
<button id="btnReload">New Game</button>
</p>
<p>
</p>
<table class="boxes">
<tr>
<td id="0" class="BoxCell">1</td>
<td id="1" class="BoxCell">2</td>
</tr>
<tr>
<td id="2" class="BoxCell">3</td>
<td id="3" class="BoxCell">4</td>
</tr>
<tr>
<td id="4" class="BoxCell">5</td>
<td id="5" class="BoxCell">6</td>
</tr>
<tr>
<td id="6" class="BoxCell">7</td>
<td id="7" class="BoxCell">8</td>
</tr>
</table>
Use jquery on( 'click' ,function());
Thats even better in terms of execution

html table to convert list or stack datastrure without javascript?

i am developer for android web App.
i using javascript interface on Android Webview.
so that, i have some problem.
how to convert html table with only javascript?
<table>
<tr>
<td> <input type=button value='test'> </input>
</td>
<td> <form> <h1> test heading </h1> </form>
</td>
<tr>
<h1> heading 2 </h1>
</tr>
<tr>
<div>
<table>
<tr>
<td> td1 </td>
<td> td2 </td>
<td> td3 </td>
</tr>
</table>
</div>
</tr>
and Javascript Code
var table_index = 0;
function node_init() {
var nodes = document.body.children;
for (var i = 0; i < nodes.length; i++) {
var node = nodes[i];
if (node.tagName == 'TABLE') {
node_init_table_name(node, ++table_index);
}
}
}
function node_init_table_name(table, index) {
table.setAttribute('node_tableName', 'table ' + index);
var cellIndex = 0;
for (var row = 0; row < table.rows.length; row++) {
for (var column = 0; column < table.rows[row].cells.length; column++) {
var cell = table.rows[row].cells[column];
cell.setAttribute('cellName', cellIndex++);
if (cell.childElementCount > 0) {
var nodes = cell.children;
var inner_table_index = 0;
for (var i = 0; i < nodes.length; i++) {
var node = nodes[i];
if (node.hasChildNodes()) {
han_initChildNodes(node);
var pNode = node.parentNode;
if (pNode) {
var hasChild = node.getAttribute('child');
var focusChild = node.getAttribute('current_child');
pNode.setAttribute('child', hasChild);
pNode.setAttribute('current_child', focusChild);
}
}
if (node.tagName == 'TABLE') {++inner_table_index;
var inner_index = index + "-" + inner_table_index;
han_init_table_name(node, inner_index);
}
}
}
}
}/* end for*/
table.setAttribute('cellCount', cellIndex);
}

Remove many table values AngularJS

I am trying to figure out how to remove all table values from 'dzviokli' that hasnt got same 'majaId' with 'maja.ID'
This is my html
<tbody>
<tr ng-repeat="maja in majas">
<td>{{maja.numurs}}</td>
<td>{{maja.iela}}</td>
<td>{{maja.pilseta}}</td>
<td>{{maja.valsts}}</td>
<td>{{maja.pasts}}</td>
<td><button ng-click="linkedDzivokli(maja)" class="dzivoklap poga">Dzivokli</button></dt>
</tr>
</tbody>
<tbody>
<tr ng-repeat="dz in dzivokli">
<td>{{dz.numurs}}</td>
<td>{{dz.stavs}}</td>
<td>{{dz.ist_sk}}</td>
<td>{{dz.iedz_sk}}</td>
<td>{{dz.pilna_plat}}</td>
<td>{{dz.dziv_plat}}</td>
</tr>
</tbody>
This is my js. The maja.ID is maja from another database and it contais value ID. Table dzivokli has value 'MajaId' and it is linked with table 'maja' value ID.
$http.get("http://localhost:20988/api/maja").success(function (response){$scope.majas = response;});
$http.get("http://localhost:20988/api/dzivoklis").success(function(response){$scope.dzivokli = response;});
var sar = $scope.dzivokli;
var index = maja.ID;
lala(sar,index);
}
function lala(sar,index)
{
for(var i = 0; i < sar.length; i++)
{
if(sar[i].MajaId != index)
{
var x = sar.indexOf(sar[i]);
}
sar.splice(x,1);
}
}
Test with this:
for (var i = 0; i < maja.length; i++) {
seekAndDestroy($scope.dzivokli,majaId, maja[i].ID);
}
function seekAndDestroy(obj, key, value){
for (var i = 0; i < obj.length; i++) {
if (obj[i][key] == value) {
obj.splice(i, 1);
break;
}
}
}
I have figured it out. Thanks jlizanab for answering :)
Here is my js
$scope.linkedDzivokli = function(maja)
{
$http.get("http://localhost:####/api/dzivoklis").success(function(response){
var garums = response.length;
for (var i = 0; i != garums; i++)
{
if (response[i].MajaId == maja.ID) {}
else
{
response.splice(response.indexOf(response[i]), 1);
garums = garums - 1;
i = i - 1;
}
}
$scope.dzivokli = response;
});
}

Categories