I'm new to Javascript and I have been trying a Javascript table with a for loop all the day. I want to get the value of a cell. I'm doing like an "Excel app". Please check what is wrong. I just fixed things in answers ....
var MatriXcel = ( function( window, undefined ) {
var matriz = [];
var matrizJson;
var row = 5;
var col = 6;
function getData(){
return matriz;
}
function addRow(){
var newCol = [];
for (var i=0; i < col; i++){
newCol.push("");
}
matriz.push(newCol);
this.draw();
}
function drawTable(){
var table = "<tr><th></th><th>A</th><th>B</th><th>C</th><th>D</th><th>E</th></tr>";
for (var i=0; i < matriz.length; i++){
table += "<tr>";
for (var x=0; x < matriz[i].length; x++){
if (x == 0){
table += "<th>"+(i+1)+"</th>";
}else{
table += "<td><input type='text' onkeyup='MatriXcel.save("+i+","+x+",this)' value='"+matriz[i][x]+"'></td>";
}
}
table += "</tr>";
}
document.getElementById("tabla").innerHTML = table;
}
function saveInfo(irow, xcol, content){
matriz[irow][xcol] = content.value;
}
function getMatch(){
var tabla = document.getElementById("tabla");
search= document.getElementById("word").value;
var re = new RegExp(search,"gi");
var row;
var col;
for (var i = 0; i< tabla.rows.length; i++){
row = tabla.rows[i];
for (var j; j<row.cells.length; j++){
col = row.cells[j];
if(re.test(row.textContent)){
row.style.color="rgb(239, 19, 109)";
alert(row.textContent);
}else if(re.test(col.textContent)){
col.style.color="rgb(79, 2, 133)";
}
}
}
}
function saveLocal(){
matrizJson = JSON.stringify(matriz);
console.log(matrizJson);
window.localStorage.table = matrizJson;
// matrizJson = JSON.parse(matrizJson);
// console.log(matrizJson);
}
function init(){
if(typeof window.localStorage.table === 'string'){
matriz = JSON.parse(window.localStorage.table);
this.draw();
}
}
return {
addRow : addRow,
draw : drawTable,
save : saveInfo,
get : getData,
local : saveLocal,
init : init,
search : getMatch,
};
} )( window );
if (window.localStorage.length == 0){
MatriXcel.addRow();
MatriXcel.addRow();
MatriXcel.addRow();
MatriXcel.addRow();
MatriXcel.addRow();
}else{
MatriXcel.init();
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>ExcelApp</title>
<link rel="stylesheet" type="text/css" href="style.css">
</head>
<body>
<input type="search" value="" placeholder="write here" id="word">
<input type="button" value="Search" id="trigger" onclick="MatriXcel.search()">
<table id="tabla">
</table>
</body>
<script type="text/javascript" src="script.js"></script>
</html>
It seems there is an issue with your way of checking regular expression.
For example, in place of this
if(re == row.value){
it should be
if(re.test(row.value)){
Additionally, please update the code as suggested by #Teemu in the comments
you've to check for col.textContent or col.innerHTML, not row.value
Related
I created table which's effect you can see there:
https://imgur.com/88vcLE6
The problem is that, when i have long "text info" the table is getting wider instead of text being broken and getting into new line and row geting extended(elongated).
Problem shown here:
https://imgur.com/3w5V03r
even when i added \n in text in moments I wanted it to break.
let newText = document.createTextNode('TEXT INFO AND VERY LONG TEXT INFO \n THAT SHOULD MAKE THE TABLE \n THE SAME THICKNESS BUT LONGER');
I read also about str.split() method but I do not know if it's suitable here.
Additionaly, I went through idea to create new table instead of row that would be formatted the way I want basing on:
Insert Table Inside a Row
How to append a childnode to a specific position
But it seems to be too sophisticated to use it there, but I cannot think of simpler solution here.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>...::: Multicast :::...</title>
<link rel="stylesheet" type="text/css" href="multicast.css">
<script src="js/jquery.min.js"></script>
<script src="js/jquery.sortElements.js"></script>
</head>
<body>
<?php
$provider = "Test_provider";
echo '<table id="my-table">';
echo '<tr><th colSpan = "3">INPUT ROW MULTICAST</th></tr>';
echo '<tr><th id="sort11">Sort A</th><th id="sort11">Sort B</th><th id="sort11">Sort C</th></tr>';
for($counter = 0; $counter <= 9; $counter++){
$provider = "Test_provider";
echo' <tr id ="'.$counter.'"><td><button onclick="specialFunc()">'.$provider.'</button></td><td>Row '.$counter.' Col '.$counter.'</td><td>Row '.$counter.' Col '.$counter.'</td></tr>';
}
echo '</table>';
?>
<script>
isFirst = true;
var testTable = document.getElementById("my-table"),rIndex,cIndex;
function addRow(rIndex) {
var currPos = rIndex;
let tableRef = document.getElementById("my-table");
let newRow = tableRef.insertRow(rIndex);
newRow.id = "open row"
let newCell = newRow.insertCell(0);
newCell.colSpan = 3;
let newText = document.createTextNode('TEXT INFO');
newCell.appendChild(newText);
newRowNumb = document.getElementById("open row").rowIndex;
console.log("new row addRow:" + newRowNumb);
}
function specialFunc(){
buttFlag = true;
for(var i = 2; i < testTable.rows.length; i++)
{
for(var j = 0; j < testTable.rows[i].cells.length; j++)
{
testTable.rows[i].cells[j].onclick = function()
{
rIndex = this.parentElement.rowIndex;
cIndex = this.cellIndex;
//console.log(rIndex,cIndex);
if(buttFlag==true){
if (isFirst ){
rIndex = rIndex+1;
addRow(rIndex);
console.log("new row first call :" + newRowNumb);
isFirst = false;
currPos = rIndex;
buttFlag = false;
}
else{
if(rIndex == (currPos - 1))
temp=1
else{
if(rIndex==1){rIndex=rIndex+1;}
if(typeof currPos != "undefined"){testTable.deleteRow(currPos);}
if(rIndex < currPos){rIndex=rIndex+1;}
addRow(rIndex);
console.log("new row second call and more:" + newRowNumb);
currPos = rIndex;
buttFlag = false;
}
}
}
}
};
}
};
</script>
<script>
//var table = $('table');
var table = $('#my-table');
$('#sort11,#sort12,#sort13')
.each(function(){
var th = $(this),
thIndex = th.index(),
inverse = false;
th.click(function(){
if (typeof newRowNumb != "undefined") {
console.log("del row sort func :" + newRowNumb);
document.getElementById("my-table").deleteRow(newRowNumb);
newRowNumb = void 0;
}
table.find('td').filter(function(){
return $(this).index() === thIndex;
}).sortElements(function(a, b){
return $.text([a]) > $.text([b]) ?
inverse ? -1 : 1
: inverse ? 1 : -1;
}, function(){
// parentNode is the element we want to move
return this.parentNode;
});
//newRowNumb = void 0;
currPos = void 0;
isFirst = true;
});
});
</script>
</body>
</html>
You can solve this issue with CSS setting max-width.
Edit: Looks like for your example it would be better to change the max-midth of tr.
td {
max-width: 200px;
min-width: 150px;
word-wrap: break-word;
}
<table border="1">
<tr>
<th>Header1</th>
<td>Value</td>
</tr>
<tr>
<th>Header</th>
<td>MMMMMMMMMMMMMMMMMMMMMMMMMMMassiveValue</td>
</tr>
</table>
You can use the CSS word-break: break-word for the respective <td> where you want the breaks. You can keep the width of the <td> as per the parent element's width.
Hoping this helps.
When creating a table with js following the following tutorial:
https://www.aspsnippets.com/Articles/Create-dynamic-Table-in-HTML-at-runtime-using-JavaScript.aspx
I'm getting the unexpected result, the table is creating the elements on the same line as the header, and I can not understand why this is happening if anyone could help me I'd be grateful.
Att,
Carlos Eduardo
//browserify index.js > bundle.js
const request = require('request')
var respRequest
var buttonTable = document.getElementById("button-table").addEventListener("click", function() {
request('https://jsonplaceholder.typicode.com/photos', function(error, response, body) {
console.log('error:', error)
console.log('statusCode:', response && response.statusCode)
//console.log('body:', body)
var content = []
content = JSON.parse(body)
var a = content.map(function(obj) {
return Object.keys(obj).sort().map(function(key) {
return obj[key]
})
})
a.unshift(["AlbumId", "id", "url", "title", "thumbnailUrl"])
var table = document.createElement("table")
table.border = "1"
var columnCount = a[0].length
var row = table.insertRow(-1)
for (var i = 0; i < columnCount; i++) {
var headerCell = document.createElement("th")
headerCell.innerHTML = a[0][i]
row.appendChild(headerCell)
}
for (var i = 1; i < a.length; i++) {
line = table.insertRow(-1)
for (var j = 0; j < columnCount; j++) {
var cell = row.insertCell(-1)
cell.innerHTML = a[i][j]
}
}
var dvTable = document.getElementById("dvTable");
dvTable.innerHTML = "";
dvTable.appendChild(table);
})
})
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<link rel="stylesheet" href="./css/style.css">
<title>Meu Site</title>
</head>
<body>
<div class="container">
<p>Gerar Relatorio</p>
<button type="button" id="button-table" class="btn btn-default ">Gerar
Relatorio</button>
<div id="dvTable"></div>
</div>
<script src="script/bundle.js"></script>
</body>
</html>
I expect that it will create a table perfectly, with header, and lines, in a way that you can read perfectly what is in the table
var row = table.insertRow(-1)
for (var i = 0; i < columnCount; i++) {
var headerCell = document.createElement("th")
headerCell.innerHTML = a[0][i]
row.appendChild(headerCell)
}
for (var i = 1; i < a.length; i++) {
line = table.insertRow(-1)
for (var j = 0; j < columnCount; j++) {
var cell = row.insertCell(-1)
cell.innerHTML = a[i][j]
}
}
In the first loop you create the header-row, stored in variable row.
in the second loop you try to create several more rows in variable line,
but you still append your cells to row.
I am working on a check-in app though Google Sheets and want to make a search function that that takes a sport name as input in an HTML form and then returns information about the sport from the sheet in a HTML table. However, when I try to test the web app, nothing happens. How can I fix this?
Here is my code:
Index.html
<!DOCTYPE html>
<html>
<head>
<?!= HtmlService.createHtmlOutputFromFile('Stylesheet').getContent(); ?>
</head>
<body>
<fieldset id="tasks-panel">
<legend>Sports</legend>
<form name="sport-form" id="sport-form">
<label for="sport-name">Search a sport by name:</label>
<input type="text" name="sport-name" id="sport-name" />
<button onclick='addTable()' id='submit-button'>Press this</button>
</form>
<p>List of things:</p>
<div id="toggle" style="display:none"></div>
</fieldset>
<?!= HtmlService.createHtmlOutputFromFile('Javascript').getContent(); ?>
</body>
</html>
Javascript.html
<script>
function addTable() {
var sportInput = $('sport-name').value();
var columnNames = ["Names", "Times"];
var dataArray = google.script.run.getSportData(sportInput);
var myTable = document.createElement('table');
$('#divResults').append(myTable);
var y = document.createElement('tr');
myTable.appendChild(y);
for(var i = 0; i < columnNames.length; i++) {
var th = document.createElement('th'),
columns = document.createTextNode(columnNames[i]);
th.appendChild(columns);
y.appendChild(th);
}
for(var i = 0 ; i < dataArray.length ; i++) {
var row= dataArray[i];
var y2 = document.createElement('tr');
for(var j = 0 ; j < row.length ; j++) {
myTable.appendChild(y2);
var th2 = document.createElement('td');
var date2 = document.createTextNode(row[j]);
th2.appendChild(date2);
y2.appendChild(th2);
}
}
}
</script>
Code.gs
//Setting up global variables
var ss = SpreadsheetApp.openById("-spreadsheetID-");
var sheet = ss.getSheetByName("Sheet1");
var sportsFromSheet = sheet.getRange("D4:D12");
var namesFromSheet = sheet.getRange("B4:B12").getValues();
var timesFromSheet = sheet.getRange("A4:A12").getValues();
var NAMES = [];
var TIMES = [];
var OUTPUT = [];
//doGet function
function doGet() {
return HtmlService.createTemplateFromFile('Index').evaluate()
.setTitle('Check In Data')
.setSandboxMode(HtmlService.SandboxMode.IFRAME);
}
//Gets both names and times of checked-in people
function getSportData(input) {
var sportInput = input;
getNamesInSport(sportInput);
getTimesInSport(sportInput);
OUTPUT = [
[NAMES],
[TIMES]
];
Logger.log(OUTPUT);
return OUTPUT;
}
//Puts the names of every person from an inputted sport into an array.
function getNamesInSport(input) {
var data = sportsFromSheet.getValues();
for (var i = 0; i < data.length; i++) {
if(data[i] == input){
NAMES.push(namesFromSheet[i][0]);
}
}
}
//Puts the times of every person from an inputted sport into an array.
function getTimesInSport(input){
var data = sportsFromSheet.getValues();
for (var i = 0; i < data.length; i ++) {
if(data[i] == input){
TIMES.push(timesFromSheet[i][0]);
}
}
}
JQuery id selectors must be prefixed with # so to grab the value from the the 'sport-name' input you'll need to select it using
var sportInput = $('#sport-name').val();
Additionally, as Robin comments above, if you want to use the JQuery library you'll need to load it, the code you've shown indicates you might not have done this?
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
</head>
Although if this were the case you'd probably be seeing a '$ is not defined' error straight away.
I so far can view the json response. Now I wanted to convert them to tables. I am using the following code to parse data about weather of cities. I am trying to use the following code.
<!DOCTYPE html>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script>
function goTo() {
$.getJSON("http://api.openweathermap.org/data/2.5/weather?key=api&format=json&q=" + link_id.value, function(result, status, jqXHR) {
var myList = (jqXHR.responseText);
var columns = addAllColumnHeaders(myList);
for (var i = 0; i < myList.length; i++) {
var row$ = $('<tr/>');
for (var colIndex = 0; colIndex < columns.length; colIndex++) {
var cellValue = myList[i][columns[colIndex]];
if (cellValue == null) {
cellValue = "";
}
row$.append($('<td/>').html(cellValue));
}
$("#excelDataTable").append(row$);
}
}
);}
function addAllColumnHeaders(myList) {
var columnSet = [];
var headerTr$ = $('<tr/>');
for (var i = 0; i < myList.length; i++) {
var rowHash = myList[i];
for (var key in rowHash) {
if ($.inArray(key, columnSet) == -1) {
columnSet.push(key);
headerTr$.append($('<th/>').html(key));
}
}
}
$("#excelDataTable").append(headerTr$);
return columnSet;
}
</script>
</head>
<body>
<h2> Search box </h2>
<input type='text' id='link_id'>
<input type='button' id='link' value='Search' onClick='goTo()'>
<table id="excelDataTable" border="1" />
<div></div>
</body>
</html>
I got the following result:
And in chrome, i can't even view that
The response I'm getting is an object not an array. Process the response as an object.
function goTo() {
$.getJSON("http://api.openweathermap.org/data/2.5/weather?key=api&format=json&q=" + link_id.value, function(result, status, jqXHR) {
var myList = (jqXHR.responseText);
myList = JSON.parse(myList);
console.log(myList);
var keys = [];
for (var key in myList) {
keys.push(key);
}
addAllColumnHeaders(myList, keys);
var row$ = $('<tr/>');
for (var i = 0; i < keys.length; i++) {
var key = keys[i];
var cellValue = myList[key];
if (cellValue == null) {
cellValue = "";
} else if (typeof cellValue == "object") {
cellValue = JSON.stringify(cellValue);
}
row$.append($('<td/>').html(cellValue));
}
$("#excelDataTable").append(row$);
});
}
function addAllColumnHeaders(myList, keys) {
var columnSet = [];
var headerTr$ = $('<tr/>');
for (var i = 0; i < keys.length; i++) {
var key = keys[i];
headerTr$.append($('<th/>').html(key));
}
$("#excelDataTable").append(headerTr$);
return columnSet;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<h2> Search box </h2>
<input type='text' id='link_id'>
<input type='button' id='link' value='Search' onClick='goTo()'>
<table id="excelDataTable" border="1" />
<div></div>
When I click each cell it will give the column, but not the row. I believe that somehow I am unable to access the parentNode, which should be td, so that I can get the correct row number.
Here is my javascript code:
function getBoard(rows, cols)
{
var board="";// ="<table>";// id=myTableId>"; //add this
var switch1 = 0;
for (x=0; x<rows; x++)
{
board +="<tr>";
for (y=0; y<cols;y++)
{
switch1 = x%2;
if (y%2 == switch1)
board +="<td class=\"" + "td1\">" ;
else
board +="<td class=\"" + "td2\">";
}
board +="</tr>";
}
return board;
}
function setEvents()
{
var cells= document.getElementsByTagName("td");
for (var x = 0; x<cells.length; x++)
{
cells[x].onclick=function () {
var col = this.cellIndex;
var row = this.ParentNode.rowIndex;
alert (row);
var info1=document.getElementById("coordinates");
var row = this.ParentNode.rowIndex;
info1.innerHTML="\"" + row +"\"";
};
}
}
window.onload = function()
{
var divGrid = document.getElementById("myTableId");
var board = getBoard(8,8);
//divGrid.innerHTML ="debug information";
divGrid.innerHTML = board;
setEvents();
}
and here is my html:
<!DOCTYPE html>
<title> Chessboard </title>
<head>
<link rel="stylesheet" href="styles.css">
<script src="view.js"></script>
<script src="model.js"></script>
</head>
<body >
<table id="myTableId">
<div id ="gridDiv"> </div>
</table>
<div id = "coordinates"></div>
</body>
yeah parentNode was ParentNode! I guess I'll need to get use to javascripts vague answers.