Table Issue in WYSIWYG Editor - javascript

I'm creating an HTML WYSIWYG editor from scratch and I have an issue when it comes to tables. Somehow, I'm able to create the pretended number of columns but only one row (without the heading). I'd be thankful if anyone could tell what's the issue.
HTML
<!DOCTYPE html>
<html>
<head>
<title>Text Editor</title>
</head>
<body>
<div id="Ribbon">
<div id="Ribbon-3">
<button class="RibbonBtn" id="TableButton" title="Insert Table"><i class="fas fa-table"></i></button>
</div>
</div>
<div id="TextArea">
<div id="WYSIWYG" contenteditable="true"></div>
</div>
</div>
</body>
</html>
JS
window.addEventListener("load",function(){
$('#TableButton').click(function(){
var colnum = prompt("Indicate the number of columns");
var rownum = prompt("Indicate the number of rows");
var table = "";
var tablehead = "";
var tablebodytext = "";
for (var i = 0; i < colnum; i++) {
tablehead += "<th>null</th>";
}
var tablebody = [];
for (var i = 0; i < rownum; i++) {
var tablebodyrow = "";
for (var i = 0; i < colnum; i++) {
tablebodyrow += "<td>null</td>";
}
tablebody += "<tr>" + tablebodyrow + "</tr>";
}
table = "<table><tr>" + tablehead + "</tr>" + tablebody+ "</table>";
document.execCommand("insertHTML",false, table);
});
},false);
I chose 5 columns and 4 rows, but instead it created 5 columns and only 1 row

I've found the error. Such a dumb mistake...
I was using the same "i" var for the nested for loop and its parent loop.
This is the right version:
$('#TableButton').click(function(){
var colnum = prompt("Indicate the number of columns:");
var rownum = prompt("Indicate the number of rows:");
var table = "";
var tablehead = "";
var tablebodytext = "";
for (var i = 0; i < colnum; i++) {
tablehead += "<th>null</th>";
}
var tablebody = [];
for (var i = 0; i < rownum; i++) {
var tablebodyrow = "";
for (var i1 = 0; i1 < colnum; i1++) {
tablebodyrow += "<td>null</td>";
}
tablebody += "<tr>" + tablebodyrow + "</tr>";
}
table = "<table><tr>" + tablehead + "</tr>" + "<tbody>" + tablebody + "</tbody>" + "</table>";
document.execCommand("insertHTML",false, table);
});

Related

javascript function not working (TableFilter library)

I'm trying to make a table in my web app filterable. The TableFilter library seems to be really good but I'm not able to make it work (only in the web app since it works with a simple html page).
this is the code of my page:
<html>
<head>
<title>Show Elements In Table Page</title>
<script src="~/tableFilter/tablefilter.js"></script>
<script src="~/tableFilter/tablefilter_all.js"></script>
<script src="~/tableFilter/tablefilter_all_min.js"></script>
<script src="~/tableFilter/tablefilter_min.js"></script>
</head>
<body id="pageBody" onload="createTable(getLocalItem('selectedTable'), 'elementsTable');
hideElement('loading');
document.getElementById('tableName').innerHTML = getLocalItem('selectedTable');
prova();">
<h3 id="loading">loading...</h3>
<div style="margin-left: 1em; margin-top: 1em;">
<h3 id="tableName"></h3>
<table align="left" border="1" cellpadding="5" cellspacing="0" id="elementsTable">
<!--the table loads with the createTable() function-->
</table>
</div>
<script language="javascript" type="text/javascript">
setFilterGrid("elementsTable");
<!--this is not working-->
</script>
</body>
</html>
this is the createTable() js function:
function createTable(tableName, tableId) {
fetch(domain + urlParameters + tableName)
.then(r => r.text())
.then(j => JSON.parse(j))
.then(o => {
var cols = getVarNames(o);
//header
var tableHtml = "<thead><tr>";
for (var i = 0; i < cols.length; i++) {
tableHtml += "<th>" + cols[i] + "</th>";
}
tableHtml += "</tr></thead>";
//body
tableHtml += "<tbody><tr>";
for (var i = 0; i < o.length; i++) {
for (var j = 0; j < cols.length; j++) {
tableHtml += "<td>" + o[i][cols[j]] + "</td>";
}
tableHtml += "</tr>";
}
tableHtml += "</tbody>";
//insertion in document
document.getElementById(tableId).innerHTML = tableHtml;
});
}
function getVarNames(list) {
var columns = [];
for (var i = 0; i < list.length; i++) {
var row = list[i];
for (var k in row) {
if ($.inArray(k, columns) == -1) {
columns.push(k);
}
}
}
return columns;
}
the table is loaded but it is not filterable. the script in the body seems to not recognize the table. how could i solve?
i solved creating my own query methods in javascript. maybe this could be helpful for someone.
var tableObject; //variable storing the json object form the api
function createTable(tableName, tableId) {
fetch(domain + urlParameters + tableName)
.then(r => r.text())
.then(j => JSON.parse(j))
.then(o => {
tableObject = o;
//insert filtering variables
var cols = getVarNames(tableObject);
//header
var tableHtml = "<thead><tr>";
for (var i = 0; i < cols.length; i++) {
tableHtml += "<th>" + cols[i] + "</th>";
}
//insert selection and filtering tools
tableHtml += "<tr>";
for (var i = 0; i < cols.length; i++) {
tableHtml += "<td><textarea class=\"filter\" rows=\"1\" placeholder=\"input\" style=\"resize: none;\"></textarea></td>";
//add some kind of tag matching the column -> maybe a class? or an id?
}
tableHtml += "</tr>";
tableHtml += "</tr></thead>";
//body
tableHtml += "<tbody id=\"tableBody\"><tr>";
for (var i = 0; i < tableObject.length; i++) {
if (objectIncludesFilters(tableObject[i], cols, getValuesFilters())) {
for (var j = 0; j < cols.length; j++) {
tableHtml += "<td>" + tableObject[i][cols[j]] + "</td>";
}
tableHtml += "</tr>";
}
}
tableHtml += "</tbody>";
//insertion in document
document.getElementById(tableId).innerHTML = tableHtml;
});
}
function getVarNames(list) {
var columns = [];
for (var i = 0; i < list.length; i++) {
var row = list[i];
for (var k in row) {
if ($.inArray(k, columns) == -1) {
columns.push(k);
}
}
}
return columns;
}
function getValuesFilters() {
const collection = document.getElementsByClassName("filter");
var values = [];
for (var i = 0; i < collection.length; i++) {
var value = collection[i].value;
values.push(value);
if (value == null) {
values.push("");
}
}
return values;
}
function objectIncludesFilters(obj, cols, filters) {
var result = true;
for (var i = 0; i < filters.length; i++) {
if (!obj[cols[i]].toLowerCase().includes(filters[i].toLowerCase())) {
result = false;
}
}
return result;
}

How can I use jQuery to randomly select one column from each row?

I have dynamically created rows and columns with jQuery. Can anyone help me on how to select a random column from each row? So far here is how my code looks like;
$(document).ready(function(){
var canva = $("#board");
var gameHolder = "<div class='gHolder'>";
var rows = 7;
var cols = 10;
function boardSetUp(){
for(var i = 0; i < rows; i++){
var row = "<div class='row'>";
for(var j = 0; j < cols; j++){
var col = "<li class='col'>";
col += "</li>";
row += col;
}
row += "</div>";
gameHolder += row;
}
gameHolder += "</div>";
canva.html(gameHolder);
}
boardSetUp();
})
You can use a comibnation of Math.floor() and Math.random() to get an integer between 1 and the amount of columns (x) per row.
Math.floor (Math.random () * x) + 1
I simplified your given example and added a funtion to select one random column per row. For this example I dynamically add a class for each selected column.
$(document).ready (function () {
var rows = 7;
var cols = 10;
var gameHolder = '';
for (var i = 0; i < rows; i++) {
gameHolder += '<div class="row">';
for(var j = 0; j < cols; j++)
gameHolder += '<div class="col"></div>';
gameHolder += '</div>';
}
$("#board").html(gameHolder);
})
function select_cols () {
var canvas = $("#board");
//reset all columns
$('.col').removeClass ('selected');
//loop through every row
canvas.find ('.row').each (function (i) {
//count columns and select random one
var count = $(this).find ('.col').size (); // $(this) is the current row
var selected = Math.floor (Math.random () * count) + 1;
//get your selected column-element
var column = $(this).find ('.col:nth-child(' + selected + ')') // :nth-child(x) is a css-selector
//do something with it. for example add a class
column.addClass ('selected');
});
}
#board {
border: 1px solid #999;
}
.row {
display: flex;
}
.col {
flex-grow: 1;
height: 10px;
border: 1px solid #999;
}
.selected {
background-color: #958;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="board"></div>
<br>
<button onclick="select_cols ();">select random columns</button>
I see that you're asking for a random column for each row, but if you'd like just a random position on the game board, you could do something like this:
$(document).ready(function(){
var canva = $("#board");
var gameHolder = "<div class='gHolder'>";
var rows = 7;
var cols = 10;
function boardSetUp(){
for(var i = 0; i < rows; i++){
var row = "<div class='row'>";
for(var j = 0; j < cols; j++){
var col = "<li class='col' id='" + i + "-" + j + "'>";
col += "</li>";
row += col;
}
row += "</div>";
gameHolder += row;
}
gameHolder += "</div>";
canva.html(gameHolder);
}
boardSetUp();
function selectRandomLocation(){
var pos = $('#' + Math.floor(Math.random() * rows) + '-' + Math.floor(Math.random() * cols));
return pos;
}
})
you can use foreach and random ,
try :
var j = 0;
$("row").each(function(){
random_col = Math.floor(Math.random() * 10);
var i = 0;
$("li").each(function(){
if(random_col == i)
/* $(this) = your random col */
alert("the random col is a number "+i+" for col number "+j);
i++;
});
j++;
});

Converting CSV input in textarea to dynamic table

This picture defines what I need
I want that the data I enter dynamically to be converted to table with each comma defining the column and the newline defining the new row.
Below is the code I have tried. Can I have a better approach to this problem?
<script>
function myFunction()
{
var x = document.getElementById("textarea").value.split(" ");
var customers = new Array();
customers.push(x[0]);
customers.push(x[1]);
customers.push(x[2]);
var table = document.createElement("TABLE");
table.border = "1";
//Get the count of columns.
var columnCount = customers[0].length;
//Add the header row.
var row = table.insertRow(-1);
for (var i = 0; i < columnCount; i++) {
var headerCell = document.createElement("TH");
headerCell.innerHTML = customers[0][i];
row.appendChild(headerCell);
}
//Add the data rows.
for (var i = 1; i < customers.length; i++) {
row = table.insertRow(-1);
for (var j = 0; j < columnCount; j++) {
var cell = row.insertCell(-1);
cell.innerHTML = customers[i][j];
}
}
var dvTable = document.getElementById("dvTable");
dvTable.innerHTML = "";
dvTable.appendChild(table);
}
</script>
<html>
<head>
<title>Player Details</title>
</head>
<body align = "center">
<h3 align = "center"><b>Input CSV</b></h3>
<p align = "center"><textarea rows="10" cols="50" name = "csv" id = "textarea"></textarea></p><br>
<button type="button" id = "convert" onclick="myFunction()">Convert</button><br>
<br>
<div id = "team"></div>
</body>
</html>
You need to split the data first using newline (\n) and then using comma (,) character.
The table can be created as string and finally inserted to the correct div.
Refer the code below to get you started.
function myFunction() {
var tbl = "<table class='table table-responsive table-bordered table-striped'><tbody>"
var lines = document.getElementById("textarea").value.split("\n");
for (var i = 0; i < lines.length; i++) {
tbl = tbl + "<tr>"
var items = lines[i].split(",");
for (var j = 0; j < items.length; j++) {
tbl = tbl + "<td>" + items[j] + "</td>";
}
tbl = tbl + "</tr>";
}
tbl = tbl + "</tbody></table>";
var divTable = document.getElementById('team');
console.log(tbl);
divTable.innerHTML = tbl;
}
I've used bootstrap for css, you may want to use your own (or not).
Refer jsFiddle here.

How to read value of Textbox which is inside table

I need to read the value of textbox which is inside the table.
Following is how I create table.
var theader = '<table border = "1" id = "MarksTable">\n';
var tbody = '';
for ( var i = 0; i < total_rows; i++) {
tbody += '<tr>';
for ( var j = 0; j < total_col; j++) {
tbody += '<td name=' + "cell" + i + j + '>';
if (i > 0) {
tbody += '<input type="text" value = "marks" name="inputcell1'+j + '">';
} else {
tbody += '<b>' + subjectList[j] + '</b>';
}
tbody += '</td>';
}
tbody += '</tr>\n';
}
var tfooter = '</table>';
document.getElementById('wrapper').innerHTML = theader
+ tbody + tfooter ;
and below is my attempt to read text box value:
function readTableData(){
var marks = [];
var table = document.getElementById("MarksTable");
var column_count = table.rows[1].cells.length;
var row = table.rows[1];
if(column_count>0){
for(var index = 0; index < column_count;index++){
marks[index] = row.cells[index].innerHTML;
}
}
return marks;
}
Here, row.cells[index].innerHTML gives the output '<input type="text" value = "marks" name="inputcell10">.
Try this:
function readTableData(){
var marks = [];
var table = document.getElementById("MarksTable");
var column_count = table.rows[1].cells.length;
var row = table.rows[1];
if(column_count>0){
for(var index = 0; index < column_count;index++){
marks[index] = row.cells[index].getElementsByName('inputcell' + index)[0].value;
//Or marks[index] = document.getElementsByName('inputcell' + index)[0].value;
}
}
return marks;
}
<!DOCTYPE html>
<html>
<head>
<style>
table, td {
border: 1px solid black;
}
</style>
</head>
<body>
<p>Click the button to add a new row at the first position of the table and then add cells and content.</p>
<div id="tableContainer">
</div>
<br>
<button onclick="myFunction()">Try it</button>
<button onclick="readTableData()"> Read it </button>
<script>
function myFunction() {
var tab = '<table id="MarksTable">';
var counter = 0;
for(i = 0; i< 4; i++){
tab = tab + '<tr><td rowspan = "4"> Dept1 </td><td> <input type="text" id="inputcell'+counter+'" value="'+i+'"/> </td></tr>';
counter++;
tab = tab+'<tr><td> <input type="text" id="inputcell'+counter+'" value="'+i+'"/> </td></tr>';
counter++;
tab = tab+'<tr><td> <input type="text" id="inputcell'+counter+'" value="'+i+'"/> </td></tr>';
counter++;
tab = tab+'<tr><td> <input type="text" id="inputcell'+counter+'" value="'+i+'"/> </td></tr>';
counter++;
}
tab = tab + '</table>';
document.getElementById("tableContainer").innerHTML = tab;
}
function readTableData(){
var val;
var table = document.getElementById("MarksTable");
var column_count = table.rows[1].cells.length;
var rowcount = table.rows.length;
alert(rowcount);
if(column_count>0){
for(var index = 0; index < rowcount;index++){
var row = table.rows[index];
val = document.getElementById("inputcell"+index);
alert(val.value);
//marks = row.cells[0].getElementsByName('inputcell').value;
//Or marks[index] = document.getElementsByName('inputcell' + index)[0].value;
}
}
alert(val);
}
</script>
</body>
</html>

JavaScript onclick programaticly not always works

I'm trying to set a onclick event handler.
from some reason this works:
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<script type="text/javascript">
function init() {
var td = document.getElementById("td");
var table = document.createElement("table");
var row = table.insertRow(0);
var cell = row.insertCell(0);
cell.innerHTML = "test";
cell.onclick = function () { alert(); };
td.appendChild(table);
}
</script>
</head>
<body id="td" onload="init()">
</body>
</html>
and when putting it in outside js file it doesn't work:
function buildChessBoard() {
var currentColor = white;
//var table = "<table>";
var table = document.createElement("table");
for (var i = 0; i < chessBoardsize / 8; i++) {
//table += "<tr>";
var row = table.insertRow(i);
for (var j = 0; j < 8; j++) {
//table += "<td class=" + currentColor + "Cell" + " id=" + (i * 8 + j) + " onclick=setCell(this)></td>";
var cell = row.insertCell(j);
cell.innerHTML = "test";
cell.onclick = function () { alert(); };
if (j != 7) {
if (currentColor == white)
currentColor = gray;
else
currentColor = white;
}
}
//table += "</tr>";
}
//table += "</table>";
//chessBoardDiv.innerHTML = table;
chessBoardDiv.appendChild(table);
}
any idea why ?

Categories

Resources