HTML/CSS/Javascript - Align Text In Table - javascript

I am trying to align the text in my table. It currently looks like this:
I would like to align the tile (in bold) in the center. Also, I am trying to get the values on the right, moved to the left.
Currently I have:
Javascript:
var table = $('<table/>',
{
id: 'table',
"class":'tables'
});
// ************************ Row 1 ************************************
row1 = $('<tr></tr>');
var head = $('<th></th>').addClass('dealHead').text(value.dealTitle);
row1.append(head);
table.append(row1);
// ********************************************************************
// ************************ Row 2 ************************************
row2 = $('<tr></tr>');
var col1 = $('<td></td>').addClass('name').text("Name: ");
var col2 = $('<td></td>').addClass('nameValue').text(value.name);
row2.append(col1);
row2.append(col2);
table.append(row2);
// ********************************************************************
// ************************ Row 3 ************************************
row3 = $('<tr></tr>');
col1 = $('<td></td>').addClass('address').text("Address: ");
col2 = $('<td></td>').addClass('addressValue').text(value.address);
row3.append(col1);
row3.append(col2);
table.append(row3);
// ********************************************************************
table.appendTo('body')
CSS:
body
{
background-color:#5CD65C;
}
.dealHead
{
text-align:center;
}
.name
{
border-top:thick double #0F0F00;
border-left:thick double #0F0F00;
border-bottom:thick double #0F0F00;
}
.nameValue
{
border-top:thick double #0F0F00;
border-right:thick double #0F0F00;
border-bottom:thick double #0F0F00;
text-align:left;
}
.address
{
border-top:thick double #0F0F00;
border-left:thick double #0F0F00;
border-bottom:thick double #0F0F00;
}
.addressValue
{
border-top:thick double #0F0F00;
border-right:thick double #0F0F00;
border-bottom:thick double #0F0F00;
text-align:left;
}
.tables
{
width="400";
border-collapse: collapse;
}
HTML
Pretty much an empty <body>
Would anyone know what I am doing wrong here?

In order to center the header you add colspan=2 that works,align the td's you have a class so add text-align-left like this
row1 = $('<tr></tr>');
var head = $('<th colspan="2"></th>').addClass('dealHead').text(value.dealTitle);
CSS
.test td {
text-align: right;
}
Example HTML
<table class="test">
<tr>
<th colspan="2">Title</th>
</tr>
<tr>
<td>data1</td>
<td>data2</td>
</tr>
</table>

CSS
.tables { width="400"; ...
should be
.tables { width: 400px; ...
In order to have both cells the same with:
.tables td { width: 50%; }
Javascript
var head = $('<th></th>').addClass('dealHead').text(value.dealTitle);
This is only one cell, make it like two:
var head = $('<th colspan="2"></th>').addClass('dealHead').text(value.dealTitle);
jsFiddle

if this is plain html, I could have made the header <th> to be of colspan=2.
similarly make your header
var head = $('<th colspan="2"></th>').addClass('dealHead').text(value.dealTitle);
hope this would help.

Related

Save content editable HTML table in multiple fields

I need to develop a HTML table where one of the table column is editable on its row and the table row is dynamic in term of the row number.
I come across a problem where when I automate the saveEdits() function, the code is not working.
Here is my code, where the 'cnt' is a dynamic numeric number. Example cnt=50
<!DOCTYPE html>
<html>
<head>
<style>
table {
font-family: arial, sans-serif;
border-collapse: collapse;
width: 100%;
}
table ,tr td{
border:1px solid #dddddd;
padding: 8px;
}
tbody {
display:block;
height:600px;
overflow:auto;
}
thead, tbody tr {
display:table;
width:100%;
table-layout:fixed;
}
thead {
width: calc( 100% - 1em )
}
tr:nth-child(even) {
background-color: #dddddd;
}
</style>
<script type="text/javascript">
function saveEdits(cnt) {
//get the editable elements.
var str_out = ''
while (cnt>0){
str1 = '\'edit' + cnt + '\': document.getElementById(\'edit' + cnt + '\').innerHTML,\n'
str_out = str_out.concat(' ', str1);
cnt--;
};
var editElems= { str_out };
alert(editElems)
//save the content to local storage. Stringify object as localstorage can only support string values
localStorage.setItem('userEdits', JSON.stringify(editElems));
}
function checkEdits(){
//find out if the user has previously saved edits
var userEdits = localStorage.getItem('userEdits');
alert(userEdits) // suppose to print {"edit1":" rpeyy7<br>","edit2":" tpruiiy<br>","edit3":" opty<br>"}
if(userEdits){
userEdits = JSON.parse(userEdits);
for(var elementId in userEdits){
document.getElementById(elementId).innerHTML = userEdits[elementId];
}
}
}
</script>
</head>
<body onload="checkEdits()">
<table id="myTable">
<thead>
<tr>
<td style="background-color:#A9A9A9" > Field#1 </td>
<td style="background-color:#A9A9A9" > Field#2 </td>
<td style="background-color:#A9A9A9" > Field#3- Each Row Under field#3 is content EditableByUser </td>
</tr>
</thead>
<tbody>
// Here is the python code that loop through a diectionary content
cnt = 0
for c in sorted(data_dict.keys()) :
cnt += 1
<tr>
<td> {0} </td> //Field#1
<td> {0} </td> //Field#2
...
...
<td id="edit{0}" contenteditable="true" onKeyUp="saveEdits({0});"> {1} </td>\n'.format(cnt,comment)]
</tr>
</table>
</body>
I'm not sure where goes wrong as when I automate the saveEdits() function with 'cnt' in while loop, the above code doesn't works for me. But when I defined each row clearly like below, the data the keyed-in are properly saved to each column.
function saveEdits(cnt) {
//get the editable elements.
var editElems = {
'edit1': document.getElementById('edit1').innerHTML,
'edit2': document.getElementById('edit2').innerHTML,
'edit3': document.getElementById('edit3').innerHTML,
};
alert(editElems) //print [object Object]
//save the content to local storage. Stringify object as localstorage can only support string values
localStorage.setItem('userEdits', JSON.stringify(editElems));
}
I would be much appreciate if someone can point out my mistake. The error is very much likely on saveEdits(cnt) function but I'm not sure how to fix that cause it I define each count 1 by 1, each update that being keyed-in is actually saved properly and able to retrieve when rerun. Thanks you!

How to change index in html element

In my code, each class will be toggled by clicking them.
I would like to understand the data,class-index, in my code,class-index is changed and class will be changed aligned with this.
But when I look at developer tool, class-index dosen't seems to be changed.
<td class="classC" data-class-index="0">Value 1</td>
<td class="classB" data-class-index="0">Value 1</td>
Considering this, I add undo button,it works as a reverse of toggle,but it didn't work well.
How can I fix it?
$(function(){
var classArray = ['classA','classB','classC'];
var arrLen = classArray.length;
$("#our_calendar td").click(function() {
var classIndex = $(this).data('class-index');
$(this).removeClass(classArray[classIndex]);
if(classIndex < (arrLen-1)) {
classIndex++;
} else {
//reset class index
classIndex = 0;
}
$(this).addClass(classArray[classIndex]);
$(this).data('class-index',classIndex);
});
$("#undo").on('click',function() {
var classIndex = $(this).data('class-index');
$(this).removeClass(classArray[classIndex]);
classIndex--;
$(this).addClass(classArray[classIndex]);
$(this).data('class-index',classIndex);
})
});
.classA {
background-color: aqua;
}
.classB {
background-color: yellow;
}
.classC {
background-color: red;
}
td {
transition-duration:0.4s ;}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table id="our_calendar">
<tr><td class="classA" data-class-index="0">Value 1</td></tr>
</table>
<button id="undo">undo</button>
With regard to the DOM not being updated, this is expected behaviour as the data() method only updates jQuery's internal cache of data attributes. It does not update the data attributes held in the relevant elements in the DOM.
With regard to your issue, the main problem is because you're using this within the #undo click handler. That will refer to the clicked button, not the td with the class on it. You just need to target the right element.
Also note that the classIndex logic can be simplified by using the modulo operator. Try this:
$(function() {
let classArray = ['classA', 'classB', 'classC'];
let arrLen = classArray.length;
let $td = $("#our_calendar td");
$td.click(function() {
let classIndex = $td.data('class-index');
$td.removeClass(classArray[classIndex]);
classIndex = ++classIndex % classArray.length;
$td.addClass(classArray[classIndex]);
$td.data('class-index', classIndex);
});
$("#undo").on('click', function() {
let classIndex = $td.data('class-index');
$td.removeClass(classArray[classIndex]);
classIndex = (--classIndex + classArray.length) % classArray.length;
$td.addClass(classArray[classIndex]);
$td.data('class-index', classIndex);
});
});
.classA { background-color: aqua; }
.classB { background-color: yellow; }
.classC { background-color: red; }
td { transition-duration: 0.4s; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table id="our_calendar">
<tr>
<td class="classA" data-class-index="0">Value 1</td>
</tr>
</table>
<button id="undo">undo</button>

JavaScript Save Table Rows added by User

I am making an Electron app that has tables, the user can add a table and change the content of the fields, but I want the input to be saved, and only if the user entered anything into them.
How would I do this? Do I need a database? Can it be done with cookies? I have tried to learn how to use cookies but have not found how to save an added element as well as the content.
function appendRow(id) {
var table = document.getElementById(id); // table reference
length = table.length,
row = table.insertRow(table.rows.length); // append table row
var i;
// insert table cells to the new row
for (i = 0; i < table.rows[0].cells.length; i++) {
createCell(row.insertCell(i), i, 'row');
}
}
function createCell(cell, text, style) {
var div = document.createElement('div'), // create DIV element
txt = document.createTextNode('_'); // create text node
div.appendChild(txt); // append text node to the DIV
div.setAttribute('id', style); // set DIV class attribute
div.setAttribute('idName', style); // set DIV class attribute for IE (?!)
cell.appendChild(div); // append DIV to the table cell
}
table {
text-align: center;
width: 400px;
}
tr:nth-child(even) {
background-color: #ccc;
}
<!DOCTYPE html>
<html>
<head>
<title>Test</title>
<link rel="stylesheet" href="test.css">
</head>
<body>
<button id="addCust" class="addSort" onclick="appendRow('custList')">add customer</button>
<table id="custListTop" contenteditable="false" style="background-color: #ccc;">
<tr>
<td style="border-top-left-radius: 5px;">Customers</td>
<td style="border-top-right-radius: 5px;">Main Location</td>
</tr>
</table>
<table id="custList" contenteditable="true">
<tr>
<td>Someone</td>
<td>something</td>
</tr>
</table>
<script src="test.js"></script>
</body>
</html>
Well how you are going to save it depends on what you want to do. If you want it to persist after your program was exited, you will need to save it on the disk or on a server somehow. You probably just want to save it into a file, though. (JSON is the most obvious choice). Otherwise, just save it into a js variable.
To get the data, I would either use a save button that reads the text of your cells, or use databinding. Later is very useful for Electron apps. You can either use a framework (like vue.js, react.js or many more) or DIY.
Former is probably easier and you will want a button to save it to the disk anyways. On the click of the button you can just go through all <tr>-elements and get their values and save them.
function save(id) {
var table = document.getElementById(id);
var trs = table.getElementsByTagName('tr'); // list of all rows
var values = []; // will be a (potentially jagged) 2D array of all values
for (var i = 0; i < trs.length; i++) {
// loop through all rows, each will be one entrie in values
var trValues = [];
var tds = trs[i].getElementsByTagName('td'); // list of all cells in this row
for (var j = 0; j < tds.length; j++) {
trValues[j] = tds[j].innerText;
// get the value of the cell (preserve newlines, if you don't want that use .textContent)
}
values[i] = trValues;
}
// save values
console.log(values);
}
function appendRow(id) {
var table = document.getElementById(id); // table reference
length = table.length,
row = table.insertRow(table.rows.length); // append table row
var i;
// insert table cells to the new row
for (i = 0; i < table.rows[0].cells.length; i++) {
createCell(row.insertCell(i), i, 'row');
}
}
function createCell(cell, text, style) {
var div = document.createElement('div'), // create DIV element
txt = document.createTextNode('_'); // create text node
div.appendChild(txt); // append text node to the DIV
div.setAttribute('id', style); // set DIV class attribute
div.setAttribute('idName', style); // set DIV class attribute for IE (?!)
cell.appendChild(div); // append DIV to the table cell
}
table {
text-align: center;
width: 400px;
}
tr:nth-child(even) {
background-color: #ccc;
}
<!DOCTYPE html>
<html>
<head>
<title>Test</title>
<link rel="stylesheet" href="test.css">
</head>
<body>
<button id="addCust" class="addSort" onclick="appendRow('custList')">add customer</button>
<button id="save" class="save" onclick="save('custList')">save</button>
<table id="custListTop" contenteditable="false" style="background-color: #ccc;">
<tr>
<td style="border-top-left-radius: 5px;">Customers</td>
<td style="border-top-right-radius: 5px;">Main Location</td>
</tr>
</table>
<table id="custList" contenteditable="true">
<tr>
<td>Someone</td>
<td>something</td>
</tr>
</table>
<script src="test.js"></script>
</body>
</html>

Javascript sorting a csv rows and displaying in table

I have a csv file which has this format:
Major;2;4;29
Major should be displayed on the 4 row 2 column.
The file can have a lot nof rows!
I have created this:
var fileInput = document.getElementById("csv"),
readFile = function () {
var reader = new FileReader();
reader.onload = function () {
document.getElementById('out').innerHTML = reader.result;
};
reader.readAsBinaryString(fileInput.files[0]);
};
fileInput.addEventListener('change', readFile);
<style type="text/css">
output {
display: block;
margin-top: 4em;
font-family: monospace;
font-size: .8em;
}
</style>
which basically takes a csv file as an input and prints all as it is raw!How can I work and divide the rows on the ";"?And I also want an honest answer what level is this for?(intern,senior?)
Here's a trivial example, it's fairly straight forward. The issue will be splitting the data, it's pretty simple if the data is simple and the delimiter unique. But if the delimiter is in the data, the splitting into values requires a little more cleverness.
This uses table.rows to get the row, then row.cells to get the cell and inserts the value. Columns and rows are zero indexed, and for rows includes the header and footer (if they exist). You can also use the tbody.rows if the header rows should be skipped.
var data = 'Major;1;2;29\nMinor;2;3;29';
function insertData(id, data) {
// Show data
console.log(data);
// Get the table
var table = document.getElementById(id);
// Split the data into records
var dataRows = data.split(/\n/);
// Split each row into values and insert in table
if (table) {
dataRows.forEach(function(s) {
var x = s.split(';');
table.rows[x[2]].cells[x[1]].textContent = x[0];
});
}
}
table {
border-collapse: collapse;
border-left: 1px solid #999999;
border-top: 1px solid #999999;
}
td, th {
border-right: 1px solid #999999;
border-bottom: 1px solid #999999;
}
<table id="t0">
<thead>
<tr>
<th>col 0<th>col 1<th>col 2
</thead>
<tbody>
<tr>
<td> <td><td>
<tr>
<td> <td><td>
<tr>
<td> <td><td>
</tbody>
</table>
<button onclick="insertData('t0', data)">Insert data</button>

two td tag don't slide side by side

Hello I develop a app where td appear and disapear side by side.
lastInsertTd = 0;
function newSlidingTd() {
tr = jQuery('#myline');
var lastTd = jQuery('#myline').children().last();
td = jQuery("<td></td>")
.attr('id', 'slidingTd' + lastInsertTd+1)
.attr('style', 'display:none;vertical-align:top;width:100%');
tr.append(td);
tdSuivant = jQuery('#slidingTd' + lastInsertTd+1);
tdActuel = jQuery('#slidingTd' + lastInsertTd);
/*animation*/
tdActuel.toggle('slide', {
direction: 'left'
}, 500);
tdSuivant.toggle('slide', {
direction: 'right'
}, 500);
lastInsertTd = lastInsertTd+1;
}
table {
width:100px
}
td {
border: black solid 1px;
width:100%
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://code.jquery.com/ui/1.11.4/jquery-ui.js"></script>
<table>
<tr id="myline">
<td id='slidingTd0' onclick="newSlidingTd()">
1
</td>
</tr>
</table>
But when I call my event, my new td doesn't slide from the right but a little bit lower. How can I go through this "bug"? (this also happen when I create div inside td)
if it's slightly lower, then most likely it's some issue with displaying whitespaces.
Try setting line-height: 0; in the parent element (tr I'd guess), or remove the whitespace between < /td >< td >

Categories