Hi friends, I want to help a group to make the table without using the pen and paper. I created the dynamic timetable with javascript, html and css. There is one thing that I found difficult, it is to make a button that allows to download the table in a pdf format in lanscape, which I found difficult, please help me!
here is the link of the code in github : https://github.com/zahiraaa/timetable
const timetable = document.getElementById("timetable");
const days = ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"];
const hours = ["7H", "13H", "20H"];
// Create table headers for days
const daysHeaderRow = document.createElement("tr");
const daysHeaderCell = document.createElement("th");
daysHeaderCell.innerHTML = "Days";
daysHeaderRow.appendChild(daysHeaderCell);
days.forEach(day => {
const dayHeaderCell = document.createElement("th");
dayHeaderCell.innerHTML = day;
dayHeaderCell.colSpan = 3;
daysHeaderRow.appendChild(dayHeaderCell);
});
timetable.appendChild(daysHeaderRow);
// Create table headers for hours
const hoursHeaderRow = document.createElement("tr");
const hoursHeaderCell = document.createElement("th");
hoursHeaderCell.innerHTML = "Hours";
hoursHeaderRow.appendChild(hoursHeaderCell);
for (let i = 0; i < days.length; i++) {
for (let j = 0; j < 3; j++) {
const hourHeaderCell = document.createElement("th");
hourHeaderCell.innerHTML = hours[j];
hoursHeaderRow.appendChild(hourHeaderCell);
}
}
timetable.appendChild(hoursHeaderRow);
// Create row for Mina
const names = ["Khalfi","Redouani", "Daki", "Hamma", "Saadane", "Boughanem", "El Ansari","Badilou","Raoui", "Chouiba", "Dahmane", "Achdad", "Bouryal", "Ettouri", "Saadouni"];
for (let name of names) {
const row = document.createElement("tr");
const nameCell = document.createElement("td");
nameCell.innerHTML = name;
row.appendChild(nameCell);
for (let i = 0; i < days.length; i++) {
for (let j = 0; j < 3; j++) {
const cell = document.createElement("td");
const select = document.createElement("select");
select.classList.add("cell");
const options = [" ", "CP", "ME", "CL", "CE", "R"];
options.forEach(option => {
const optionElement = document.createElement("option");
optionElement.value = option;
optionElement.innerHTML = option;
select.appendChild(optionElement);
});
cell.appendChild(select);
row.appendChild(cell);
}
}
timetable.appendChild(row);
}
function exportCSV() {
var rows = document.querySelectorAll("#timetable tr");
var csvData = [];
for (var i = 0; i < rows.length; i++) {
var rowData = [];
var cells = rows[i].querySelectorAll("td, th");
for (var j = 0; j < cells.length; j++) {
const select = cells[j].querySelector("select");
if(select){
rowData.push(select.value);
}else{
rowData.push(cells[j].innerText);
}
}
csvData.push(rowData);
}
var csv = Papa.unparse(csvData);
var csvData = new Blob([csv], {type: 'text/csv;charset=utf-8;'});
var csvURL = null;
if (navigator.msSaveBlob) {
csvURL = navigator.msSaveBlob(csvData, 'timetable.csv');
} else {
csvURL = window.URL.createObjectURL(csvData);
}
var tempLink = document.createElement('a');
tempLink.href = csvURL;
tempLink.setAttribute('download', 'timetable.csv');
tempLink.click();
// Convert the CSV data to a PDF and download it
var pdf = new jsPDF('l','mm','a4');
pdf.addPage();
pdf.text(csv, 10, 10);
pdf.save('timetable.pdf');
}
#timetable th {
border: 1px solid #ddd;
padding: 8px;
text-align: center;
background-color: #006699; /* bleu foncé /
}
#timetable tr:nth-child(even) {
background-color: #E6E6FA; / lavande */
}
/* Mise en page globale */
body {
background-color: #f1f1f1;
font-family: Arial, sans-serif;
margin: 0;
padding: 0;
}
/* Style de la barre de navigation */
nav {
background-color: #333;
color: #fff;
display: flex;
justify-content: space-between;
padding: 10px 20px;
}
nav a {
color: #fff;
text-decoration: none;
margin-right: 10px;
}
/* Style de la section principale */
main {
padding: 20px;
}
/* Style des titres */
h1, h2, h3 {
color: #333;
text-align: center;
margin-bottom: 20px;
}
/* Style des paragraphes */
p {
line-height: 1.5;
margin-bottom: 20px;
}
/* Style des images */
img {
max-width: 100%;
}
<table id="timetable">
<body>
<tr>
<td>
<link href="table.css" rel="stylesheet">
<script src="table.js"></script>
<form action="table.php" method="post">
</td>
<tr>
<button onclick="exportCSV()">Export CSV</button>
<script src="https://cdnjs.cloudflare.com/ajax/libs/PapaParse/5.1.0/papaparse.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/FileSaver.js/1.3.8/FileSaver.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jspdf/1.5.3/jspdf.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/FileSaver.js/1.3.8/FileSaver.min.js"></script>
<button onclick="exportPDF()">Export PDF</button>
<script src="https://cdnjs.cloudflare.com/ajax/libs/pdfmake/0.1.77/pdfmake.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/pdfmake/0.1.77/pdfmake.min.vfs.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/pdfmake/0.1.77/vfs_fonts.js"></script>
<button id="download-pdf-button">Télécharger en PDF</button>
<script>
var downloadButton = document.getElementById("download-pdf-button");
downloadButton.addEventListener("click", downloadPDFWithPDFMake);
</script>
</body>
Nice idea
The csv heading would perhaps be better as Days,,Monday,,,Tuesday,,,Wednesday,,,Thursday,,,Friday,,,Saturday,,,Sunday, since csv does not carry merged fields.
It works well printed landscape by browser but for jsPDF you need to apply it again at the time of add page
pdf.addPage();
defaults to a4,p so
pdf.addPage('a4','l');
should work.
For custom shapes and full syntax visibility use
pdf.addPage([841.89, 595.28],"landscape");
Related
Trying to create a table with data-attributes when clicking on a link
The problem is most likely in this code
I can not understand how to rewrite the data in the table.
Now the data is sequentially added to the table.
My code - https://jsfiddle.net/347x8bwq/
(function() {
'use strict';
function createTable() {
let link = document.querySelectorAll('.link');
let block = document.querySelector('.block');
let blockTable = document.querySelector('.table');
for (let i = 0; i < link.length; i++) {
let links = link[i];
links.addEventListener('click', function(e) {
e.preventDefault();
let linkData = this.dataset;
for (let j in linkData) {
let tableRow = document.createElement('tr');
let arr = linkData[j].split('|');
for (let k = 0; k < arr.length; k++) {
let tableCol = document.createElement('td');
tableCol.innerHTML = arr[k];
tableRow.appendChild(tableCol);
}
blockTable.appendChild(tableRow);
}
});
}
}
createTable();
Desired behavior - when clicking on a link each time - a new table was created
Before you append your tableRow to the blockTable, clear its innerHTML.
(function() {
'use strict';
function createTable() {
let link = document.querySelectorAll('.link');
let block = document.querySelector('.block');
let blockTable = document.querySelector('.table');
for (let i = 0; i < link.length; i++) {
let links = link[i];
links.addEventListener('click', function(e) {
e.preventDefault();
let linkData = this.dataset;
blockTable.innerHTML = "";
for (let j in linkData) {
let tableRow = document.createElement('tr');
let arr = linkData[j].split('|');
for (let k = 0; k < arr.length; k++) {
let tableCol = document.createElement('td');
tableCol.innerHTML = arr[k];
tableRow.appendChild(tableCol);
}
blockTable.appendChild(tableRow);
}
});
}
}
createTable();
})();
.table {
width: 100%;
table-layout: fixed;
}
td {
border: 1px solid #ccc;
}
.link {
display: block;
margin-bottom: 5px;
}
.block {
padding: 25px;
border: 1px solid #000;
}
Link 1
Link 2
Link 3
<div class="block">
<table class="table">
<tr>
<td>Атрибут1</td>
<td>Title</td>
</tr>
<tr>
<td>Атрибут2</td>
<td>Subtitle</td>
</tr>
<tr>
<td>Атрибут3</td>
<td>1234</td>
</tr>
</table>
</div>
See - https://jsfiddle.net/2wvm6de8/
You have to clear the table before adding a new elements. Just add blockTable.innerHTML = ''; after e.preventDefault();
https://jsfiddle.net/vLm60kzq/
I am new to JavaScript, and decided to do some practice with displaying n rows of Pascal's triangle. I have everything working, and the rows are displayed in the console, however when I try to push the currentRow to the array of triangle, nothing shows up on the page. Here is how I am attempting to do so:
if (typeof currentRow !== 'undefined') {
console.log('Row ', i - 2);
currentRow = currentRow.join(' ');
console.log(currentRow);
console.log(triangle);
triangle.push('n', currentRow)
triangle = triangle.join('');
}
Any help/advice would be apreciated. I am sure this code is not that efficient (I know it is not optimal to just write out the first 3 rows). Below is a code snippet, and a jsfiddle.
https://jsfiddle.net/keuo8za0/
var row0 = [1];
var row1 = [1, 1];
var row2 = [1, 2, 1];
row0 = row0.join(' ');
row1 = row1.join(' ');
row2 = row2.join(' ');
var triangle = [row0];
triangle.push('\n', row1);
triangle.push('\n', row2);
triangle = triangle.join('');
lastRow = [1, 2, 1];
var submit = document.getElementById('submit');
function buildTriangle(pascalNumber) {
for (let i = 4; i < pascalNumber; i++) {
if (typeof currentRow !== 'undefined') {
console.log('Row ', i - 2);
currentRow = currentRow.join(' ');
console.log(currentRow);
console.log(triangle);
}
var x = i;
var currentRow = [1, 1];
for (let y = 1; y + 1 < x; y++) {
var nextNumber = (lastRow[y - 1] + lastRow[y]);
currentRow.splice(1, 0, nextNumber);
}
lastRow = currentRow;
}
}
function drawTriangle() {
document.getElementById('triangle').innerText = triangle;
}
submit.onclick = function() {
var rownum = document.getElementById('pn').value;
buildTriangle(rownum - 1);
drawTriangle();
return false;
}
body {
background: #4286f4;
font-family: arial;
}
h1 {
font-size: 36px;
text-align: center;
}
h1:hover {
color: #ff35c5;
}
form {
font: sans-serif;
text-align: center;
}
p {
font-size: 36px;
font: sans-serif;
text-align: center;
}
#map {
margin: 0 auto;
width: 80%;
height: 80%;
}
<html>
<head>
<title>Pascal's Triangle</title>
<link rel="stylesheet" href="fancy.css" />
</head>
<body>
<h1>Pascal's Triangle</h1>
<form id='numberOfRows'>
Number of Rows:<br>
<input id='pn' type='number'><br>
<button id='submit'>Submit</button>
</form>
<p id='triangle'></p>
<script src="triangler.js"></script>
</body>
</html>
Interesting... I did it row by row. Found really good help from google..
<style>
body {
background: #4286f4;
font-family: arial;
}
h1 {
font-size: 36px;
text-align: center;
}
h1:hover {
color: #ff35c5;
}
form {
font: sans-serif;
text-align: center;
}
p {
font-size: 36px;
font: sans-serif;
text-align: center;
}
#map {
margin: 0 auto;
width: 80%;
height: 80%;
}
</style>
<h1>Pascal's Triangle</h1>
<form id='numberOfRows'>
Number of Rows:<br>
<input id='pn' type='number'><br>
<button id='submit'>Submit</button>
</form>
<p id='triangle'></p>
<script>
var div = document.getElementById('triangle');
submit.onclick = function() {
div.innerHTML = "";
var rownum = document.getElementById('pn').value;
printPascal(rownum);
return false;
};
function printPascal(n) {
// Iterate through every line and
// print entries in it
for (var line=0; line < n; line++)
{
var lineHTML = "<div class='text-center'>";
// Every line has number of
// integers equal to line
// number
for (var i = 0; i <= line; i++) {
lineHTML += "" + binomialCoeff(line, i) + " ";
}
lineHTML += "</div>\n";
div.innerHTML += lineHTML;
}
}
// for details of this function
function binomialCoeff(n, k)
{
var res = 1;
if (k > n - k)
k = n - k;
for (var i = 0; i < k; ++i)
{
res *= (n - i);
res /= (i + 1);
}
return res;
}
</script>
I need to get a text file from server and display its contents in a table.Tried this code couldnt figure out whats wrong...........................................................................................................................................................................................................
<!DOCTYPE html>
<html>
<meta charset="UTF-8">
<head>
<style type="text/css">
body
{
font-family: Arial;
font-size: 10pt;
}
table
{
border: 1px solid #ccc;
margin: auto;
empty-cells: hide;
}
table th
{
background-color: AQUA;
color: #333;
font-weight: bold;
}
table th, table td
{
padding: 5px;
border: 1px solid #ccc;
border-color: #ccc;
}
tr:hover {background-color: #f5f5f5;}
</style>
</head>
<body>
<div align = center>
<input type="text" id="filter" placeholder="Search" title="Type a name" >
</div>
<div id="demo" align = center>
</div>
<script>
window.onload = function() {
var demo = document.getElementById("demo");
if(window.XMLHttpRequest){
var xhttp = new XMLHttpRequest();
}
else{
var xhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
//xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200 || this.status == 0) {
var responseText= xhttp.responseText;
console.log(this.responseText);
document.getElementById("filter").onkeyup = filterRows;
var ROW_DELIMITER = "\n",
CELL_DELIMITER = " ";
var tableObj = {
headers: ["Time", "Duration", "Client address", "Result codes", "Bytes", "request method", "URL", "user",
"Hierarchy code", "Type"],
rows: []
};
}
function convert(responseText) {
tableObj.rows = convertToArray(responseText)
buildTable(tableObj.headers, tableObj.rows);
};
function convertToArray(text) {
return text.split(ROW_DELIMITER).map(function(row) {
return row.split(CELL_DELIMITER);
});
}
function filterRows() {
var input = this;
var rows = tableObj.rows.filter(function(row) {
var matches = row.filter(function(cell) {
return cell.toUpperCase().indexOf(input.value.toUpperCase()) > -1;
});
return matches.length > 0;
});
buildTable(tableObj.headers, rows);
}
function sortRows() {
var th = this;
var index = th.dataset.index;
tableObj.rows.sort(function(rowA, rowB) {
var textA = rowA[index].toUpperCase(),
textB = rowB[index].toUpperCase();
if (textA < textB) {
return -1;
}
if (textA > textB) {
return 1;
}
return 0;
});
buildTable(tableObj.headers, tableObj.rows);
}
function buildTable(headers, rows) {
var table = document.createElement('table');
var tr = document.createElement('tr');
table.appendChild(tr);
for (var i = 0; i < headers.length; i++) {
th = document.createElement('th');
tr.appendChild(th);
th.innerHTML = headers[i];
th.onclick = sortRows;
th.dataset.index = i;
}
for (var j = 0; j < rows.length; j++) {
tr = document.createElement('tr');
table.appendChild(tr);
for (var k = 0; k < rows[j].length; k++) {
var td = document.createElement('td');
tr.appendChild(td);
td.innerHTML = rows[j][k];
td.dataset.index = k;
}
}
demo.innerHTML = '';
demo.appendChild(table);
}
convert(responseText);
xhttp.open("GET", "https://www.w3.org/TR/PNG/iso_8859-1.txt", true);
xhttp.send(null);
};
</script>
</body>
</html>
My code look like this, It should have created a table when the "submitButton" was clicked but it doesn't do so. Here is my code:
submitButton.addEventListener("click", () => {
var newTable = document.createElement("table");
for(let i = 0; i < parseInt(numOfStudents); i++){
var newRow = document.createElement("tr");
var newInput = document.createElement("td");
var newInput2 = document.createElement("td");
document.newRow.appendChild(newInput);
document.newRow.appendChild(newInput2);
document.newTable.appendChild(newRow);
document.body.appendChild(newTable);
}
});
You can't access elements with body. you need to use DOM functions like getElementById etc.. if its a new created elements as in your loop you can append to them directly as below
var numOfStudents=10
submitButton=document.getElementById("submitButton")
submitButton.addEventListener("click", () => {
var newTable = document.createElement("table");
for(let i = 0; i < parseInt(numOfStudents); i++){
var newRow = document.createElement("tr");
var newInput = document.createElement("td");
var newInput2 = document.createElement("td");
newRow.appendChild(newInput);
newRow.appendChild(newInput2);
newTable.appendChild(newRow);
document.body.appendChild(newTable);
}
});
<button id="submitButton" >button</button>
U just need to add some text into it..otherwise you won't see it (unless you open the dev console).
Here is an example:
// Helpers
const createElement = el => document.createElement(el)
const createText = text => document.createTextNode(text)
// Create rows
const addStudentRows = students => {
const $body = document.querySelector('body')
const $table = createElement('table')
for (let i = 0; i < students;i++ ) {
let $td1 = createElement('td')
let $td2 = createElement('td')
$td1.appendChild(createText('Hello'))
$td2.appendChild(createText('World'))
let $tr = createElement('tr')
$tr.appendChild($td1)
$tr.appendChild($td2)
$table.appendChild($tr)
}
$body.appendChild($table)
}
// Event listener
document.querySelector('button')
.addEventListener('click', e => addStudentRows(1))
table {
margin-bottom: 10px;
}
table tr td {
padding: 10px;
border-right:1px solid #f0f0f0;
border-top: 1px solid #f0f0f0;
border-bottom: 1px solid #f0f0f0;
}
table tr td:first-child {
border-left:1px solid #f0f0f0;
}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
</head>
<body>
<button>Click here</button>
</body>
</html>
As I'm a newbie, I'm trying to create a simple calendar using JavaScript and JQuery without using any plugin. I'm trying to;
get the event name written on the calendar using the dataArray
generate random dates (ie. Calendar.Generate(data) ) and compare,
a) if they match with the dates at current month then add as a new event
b) if they don't match then show up an error message
But till now, I couldn't manage it. Any help would be appreciated. Thank you..
<head>
<link rel="stylesheet" href="https://ajax.googleapis.com/ajax/libs/jqueryui/1.12.0/themes/smoothness/jquery-ui.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.11.4/jquery-ui.min.js"></script>
<style type="text/css">
#cal-container{
padding: 10px;
width: 950px;
height:%100;
text-align: center;
border: 1px solid #00F;
border-radius: 10px;
font-size: 16px;
font-family: Arial;
background-color: #ccc;
}
#cal-container > div{
padding: 5px 45px;
margin-bottom: 10px;
}
#cal-month-year{
margin: 5px;
font-size:25px;
font-weight:bold;
}
#cal-dates>table>tr>td{
padding: 30px;
border: 1px solid #000;
width:100px;
}
</style>
</head>
<body>
<div id="cal-container">
<div id="cal-header">
<span id="cal-month-year"></span>
</div>
<div id="cal-dates">
</div>
</div>
<script>
window.onload = function simpleCalendar(){
var time = new Date();
var month_name = ['January','February','March','April','May','June','July','August','September','October','November','December'];
var month = time.getMonth();
var year = time.getFullYear();
var first_date = month_name[month] + " " + 1 + " " + year;
var foo = new Date(first_date).toDateString();
var first_day = foo.substring(0, 3);
var day_name = ['Mon','Tue','Wed','Thu','Fri','Sat','Sun'];
var day_number = day_name.indexOf(first_day);
var days = new Date(year, month+1, 0).getDate();
var calendar = get_calendar(day_number, days);
document.getElementById("cal-month-year").innerHTML = month_name[month]+" "+year;
document.getElementById("cal-dates").appendChild(calendar);
}
function get_calendar(day_number, days){
var table = document.createElement('table');
var tr = document.createElement('tr');
//first row
for(var col=0; col<=6; col++){
var td = document.createElement('td');
var gun = ['Monday', 'Tuesday', 'Wednesday', 'Thrusday', 'Friday', 'Saturday', 'Sunday']
td.innerHTML = gun[col];
tr.appendChild(td);
}
table.appendChild(tr);
//Second row
tr = document.createElement('tr');
var col;
for(col=0; col<=6; col++){
if(col == day_number){
break;
}
var td = document.createElement('td');
td.innerHTML = "";
tr.appendChild(td);
}
var count = 1;
for(; col<=6; col++){
var td = document.createElement('td');
td.innerHTML = count;
count++;
tr.appendChild(td);
}
table.appendChild(tr);
//other rows
for(var row=3; row<=7; row++){
tr = document.createElement('tr');
for(var col=0; col<=6; col++){
if(count > days){
table.appendChild(tr);
return table;
}
var td = document.createElement('td');
td.innerHTML = count;
count++;
tr.appendChild(td);
}
table.appendChild(tr);
}
return table;
var dataArray = [
{"title":"Party", "startdate":"2016/09/05"},
{"title":"Workshop JS", "startdate":"2016/09/15","enddate":"2016/09/18"},
{"title":"Math Quiz", "startdate":"2016/09/23"},
{"title":"Code Camp", "startdate":"2016/09/22","enddate":"2016/09/25"}
];
for(var row=0; row<=6; row++){
for(var col=0; col<=6; col++){
for (var k=0; k<=dataArray.length; k++){
if(table[row][col] == dataArray[k].startdate){
table[row][col].appendChild(dataArray[k].title);
}
}
}
}
return table;
}
</script>
</body>