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>
Related
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");
I'm creating a homework calculator. I need to recursively create form elements, and found out how to make a recursively creating table. How do I turn the spaces in that table into form elements that create themselves recursively? If this isn't clear, please tell me.
<table id="xTable"></table>
<script>
var rQty = parseInt(prompt("Number of Rows"), 10);
var cQty = parseInt(prompt("Number of Columns"), 10);
var table = document.getElementById("xTable");
for (let i = 0; i < rQty; i++) {
var row = table.insertRow();
for (let j = 0; j < cQty; j++) {
var cell = row.insertCell();
cell.textContent = "I want to make this into a recursive form creator ";
}
}
</script>
<style>
td {
border: 2px ridge #333;
text-align: center;
}
</style>
It's rather simple, just create the elements you want to insert into the cells with document.createElement, then set the properties you want them to have and use cell.appendChild to place them into the cell.
This example creates <input type="text"> elements:
var rQty = parseInt(prompt("Number of Rows"), 10);
var cQty = parseInt(prompt("Number of Columns"), 10);
var table = document.getElementById("xTable");
for (let i = 0; i < rQty; i++) {
var row = table.insertRow();
for (let j = 0; j < cQty; j++) {
var cell = row.insertCell();
var input = document.createElement('input');
input.type = 'text';
input.name = 'input_r' + i + '-c' + j;
cell.appendChild(input);
}
}
td {
border: 2px ridge #333;
text-align: center;
}
<table id="xTable"></table>
I have a table with black and white cells and I want to create a button which changes the colors of cells.
I have done it by using for loop jsfiddle.net
Now, I dont want to use the function below. Is it possible to change only the class atribute of whole table to change class of all td tag's?
function changeClors() {
var cells = document.getElementsByTagName('td');
for (var i = 0; i < cells.length; i++) {
cSwap(cells[i])
}
Yes it's possible you just need a css class for the table to do it and a function to toggle this class with your table.
This is how should be your css defined:
.myTable td{
background: gray;
}
And this is the JS function to toggle it in the table:
function toggleClass(){
var table = document.querySelector("table");
if(table.className !== "myTable"){
table.className = "myTable";
}else{
table.className = '';
}
}
Demo:
This is an updated Demo:
function cSwap(cell) {
if (cell.className == "t")
cell.className = "t2";
else if (cell.className == "t2")
cell.className = "t";
}
function tableCreate(n) {
var body = document.getElementsByTagName('body')[0];
var tbl = document.createElement('table');
tbl.setAttribute('onclick', 'cSwap(event.target)');
for (var i = 0; i < n; i++) {
var tr = document.createElement('tr');
for (var j = 0; j < n; j++) {
var td = document.createElement('td');
tr.appendChild(td)
td.classList.add('t');
}
tbl.appendChild(tr);
}
body.appendChild(tbl);
}
function changeClors() {
var cells = document.getElementsByTagName('td');
for (var i = 0; i < cells.length; i++) {
cSwap(cells[i])
}
}
tableCreate(5);
function toggleClass() {
var table = document.querySelector("table");
if (table.className !== "myTable") {
table.className = "myTable";
} else {
table.className = '';
}
}
td {
border: 1px solid black;
border-collapse: collapse;
padding: 28px;
}
.t {
background: white
}
.t2 {
background: black
}
.myTable td {
background: gray;
}
<body>
<input type="button" value="Change colors" onclick="changeClors()">
<input type="button" value="Change table" onclick="toggleClass()">
</body>
Instead of using the for loop, try toggling the invert class name on the table element. Then adjust the css accordingly, as in the snippet below:
function cSwap(cell) {
if (cell.className == "t")
cell.className = "t2";
else if (cell.className == "t2")
cell.className = "t";
}
function tableCreate(n) {
var body = document.getElementsByTagName('body')[0];
var tbl = document.createElement('table');
tbl.setAttribute('onclick', 'cSwap(event.target)');
tbl.setAttribute('id', 'myTable');
for (var i = 0; i < n; i++) {
var tr = document.createElement('tr');
for (var j = 0; j < n; j++) {
var td = document.createElement('td');
tr.appendChild(td)
td.classList.add('t');
}
tbl.appendChild(tr);
}
body.appendChild(tbl);
}
function changeClors() {
var table = document.getElementById('myTable');
table.classList.toggle('invert')
}
tableCreate(5);
td {
border: 1px solid black;
border-collapse: collapse;
padding: 28px;
}
.t {
background: white
}
.t2 {
background: black
}
.invert .t {
background: black
}
.invert .t2 {
background: white
}
<body>
<input type="button" value="Change colors" onclick="changeClors()">
</body>
If you're looking to just change the colors of the cells, you could toggle the class of the table and then use CSS selectors on the cells like the following:
.table-dark td { background-color: #000; }
.table-light td { background-color: #fff; }
I have to make a game in which there is an 8x8 table and a coin displays on them(more than at 10 positions at a time) for 3000milliseconds on different position simultaneously. The coin display should start at a click of "Start" button and it continues for 1minute. My problem is that I am not able to make a random function which generates images randomly on different positions.it is giving some error of appendchild undefined.I want my image to display randomly on different positions),Here what I've tried so far.I've just started learning JS so please don't judge my code & i'm posting this again because i didn't get any response in my previous post.
I had "display:none;" all the coins and i want a random function at multiple positions on which the coins displays block.
PS:I can't use any Jquery and remove the mistakes done previously
function tableCreate(){
var body = document.body;
var tbl = document.createElement('table');
tbl.style.width = '730px';
tbl.style.height = '650px';
tbl.style.border = '4px solid grey';
tbl.style.display = 'inline-block';
for(var i = 0; i < 8; i++){
var tr = tbl.insertRow();
for(var j = 0; j < 8; j++){
var td = tr.insertCell();
var div = document.createElement('div');
td.appendChild(div);
div.innerHTML = '<img src="coin.png" alt="coin.png" class="coin_img" id="coin_image">';
td.style.border = '1px solid black';
td.style.width = '85px';
td.style.height = '75px';
td.id = 'r' + i + 'c' + j;
}
}
body.appendChild(tbl);
}
function onTimer() {
var seconds = 60;
function tick() {
var counter = document.getElementById("counter");
seconds--;
counter.innerHTML = "<h1>Time Left:-"+"0:" + (seconds < 10 ? "0" : "") + String(seconds)+"</h1>";
if( seconds > 0 ) {
setTimeout(tick, 1000);
} else {
alert("Game over");
}
}
tick();
setInterval(function(){
var tbl = document.createElement('table');
var randomNumber = Math.floor(Math.random() * 7);
var tr = tbl.getElementsByTagName("tr")[randomNumber];
var td = tbl.getElementsByTagName("td")[randomNumber];
var img = tbl.getElementById("coin_image");
td[randomNumber].appendChild(img);
img.style.display = "block";
}, 3000);
}
function onRestart()
{
location.reload();
}
.button_class
{
float: left;
display: inline-block;
width: 400px;
}
.btn
{
width: 140px;
height: 50px;
margin: 20px;
font-size: 16px;
background-color:
}
.coin_img
{
width: 100%;
height: 70px;
display: none;
}
.counter_div
{
margin-left: 20px;
}
<body onload="tableCreate()">
<div class="button_class">
<button type="button" name="start_button" class="start_button btn" id="st_button" onclick="onTimer()">Start</button>
<button type="button" name="restart_button" class="restart_button btn" id="rs_button" onclick="onRestart()">Restart</button>
<div class="counter_div" id="counter">
<h1>Total Time:-1:00</h1>
</div>
</div>
</body>
i don't know exactly what you are looking for but it may works using same id multiple times is not a good choice
<script type="text/javascript">
function tableCreate(){
var body = document.body;
var tbl = document.createElement('table');
tbl.style.width = '730px';
tbl.style.height = '650px';
tbl.style.border = '4px solid grey';
tbl.style.display = 'inline-block';
for(var i = 0; i < 8; i++){
var tr = tbl.insertRow();
for(var j = 0; j < 8; j++){
var td = tr.insertCell();
var div = document.createElement('div');
td.appendChild(div);
div.innerHTML = '<img src="coin.png" alt="coin.png" class="coin_img" id="coin_image'+i+'">';
td.style.border = '1px solid black';
td.style.width = '85px';
td.style.height = '75px';
td.id = 'r' + i + 'c' + j;
}
}
body.appendChild(tbl);
}
function onTimer() {
var seconds = 60;
function tick() {
var counter = document.getElementById("counter");
seconds--;
counter.innerHTML = "<h1>Time Left:-"+"0:" + (seconds < 10 ? "0" : "") + String(seconds)+"</h1>";
if( seconds > 0 ) {
setTimeout(tick, 1000);
} else {
alert("Game over");
}
}
tick();
setInterval(function(){
var tbl = document.createElement('table');
var randomNumber = Math.floor(Math.random() * 7);
//var tr = tbl.getElementsByTagName("tr")[randomNumber];
//var td = tbl.getElementsByTagName("td")[randomNumber];
var img = document.getElementById("coin_image"+randomNumber+"");
//td[randomNumber].appendChild(img);
img.style.display = "block";
}, 3000);
}
function onRestart()
{
location.reload();
}
I think I could tweak your code:
function tableCreate(){
var body = document.body;
var tbl = document.createElement('table');
tbl.id = 'myTable';
tbl.style.width = '730px';
tbl.style.height = '650px';
tbl.style.border = '4px solid grey';
tbl.style.display = 'inline-block';
for(var i = 0; i < 8; i++){
var tr = tbl.insertRow();
for(var j = 0; j < 8; j++){
var td = tr.insertCell();
var div = document.createElement('div');
td.appendChild(div);
div.innerHTML = '<img src="http://icons.iconarchive.com/icons/awicons/vista-artistic/128/coin-icon.png" alt="coin.png" class="coin_img" id="coin_image">';
td.style.border = '1px solid black';
td.style.width = '85px';
td.style.height = '75px';
td.id = 'r' + i + 'c' + j;
}
}
body.appendChild(tbl);
}
function onTimer() {
var seconds = 60;
function tick() {
var counter = document.getElementById("counter");
seconds--;
counter.innerHTML = "<h1>Time Left:-"+"0:" + (seconds < 10 ? "0" : "") + String(seconds)+"</h1>";
if( seconds > 0 ) {
setTimeout(tick, 1000);
} else {
alert("Game over");
}
}
tick();
setInterval(function(){
var tbl = document.getElementById('myTable');
var randomNumber = Math.floor(Math.random() * 7);
var tr = Array.prototype.slice.call(tbl.getElementsByTagName("tr"))[randomNumber];
var td = Array.prototype.slice.call(tr.getElementsByTagName("td"))[randomNumber];
var img = document.getElementById("coin_image");
td.appendChild(img);
img.style.display = "block";
}, 3000);
}
function onRestart()
{
location.reload();
}
.button_class
{
float: left;
display: inline-block;
width: 400px;
}
.btn
{
width: 140px;
height: 50px;
margin: 20px;
font-size: 16px;
background-color:
}
.coin_img
{
width: 100%;
height: 70px;
display: none;
}
.counter_div
{
margin-left: 20px;
}
<body onload="tableCreate()">
<div class="button_class">
<button type="button" name="start_button" class="start_button btn" id="st_button" onclick="onTimer()">Start</button>
<button type="button" name="restart_button" class="restart_button btn" id="rs_button" onclick="onRestart()">Restart</button>
<div class="counter_div" id="counter">
<h1>Total Time:-1:00</h1>
</div>
</div>
</body>
Your inaccuracies:
add an id to the table when you initially create it in function tableCreate() like tbl.id ='myTable';
variable tbl in onTimer() function shoudn't contain a new table but
rather the existing one like var tbl = document.getElementById('myTable');
functions like getElementsByTagName("tr") return HTMLCollections,
not arrays. To convert it into array use
Array.prototype.slice.call(tbl.getElementsByTagName("tr"))
If I am not mistaken, you can call getElementById only on
document, so it should be var img = document.getElementById("coin_image");, not var img =tbl.getElementById("coin_image");
td variable in onTimer's interval already contains the td
element, no need to add an index. So, it should be
td.appendChild(img);
In order to avoid placing all the coins in the same row, change var
td = Array.prototype.slice.call(tbl.getElementsByTagName("td"))[randomNumber];
to var td = Array.prototype.slice.call(tr.getElementsByTagName("td"))[randomNumber];
It makes your code work, but there are some other, lets say, logical problems because the coins do not disappear from the cells. Also they only appear on cells with coordinates like (0,0) (2,2) (4,4) etc. because you generate the random number only once and then use it for both - row and column. I don't know maybe it is what you want. If not, work on it too.
i am trying to create the table using js in a specific location of the page
i m getting the output but also getting an error undefind before the result
before the table creation an error is shown undefine any solution for this
<script>
function tab()
{
var x=4;
function tabb(){
var table = document.createElement('table');
table.id="a-table";
for (var i = 1; i < x; i++){
var tr = document.createElement('tr');
tr.id="myrow";
var td1 = document.createElement('td');
var td2 = document.createElement('td');
tr.appendChild(td1);
tr.appendChild(td2);
table.appendChild(tr);
}
document.body.appendChild(table);
}
document.getElementById("tab").innerHTML=tabb();
var cells = document.getElementById("a-table").getElementsByTagName("td");
var i=0;
for(i = 0; i < x+1; i++){
var cell = cells[i];
cell.innerHTML = "<img class=img1 src=faculty/comm/"+i+".jpg>";
}
}
</script>
<style>
td {
border: solid 1px #000;
border-style: none solid solid none;
padding: 10px;
border-radius:8px;
}
</style>
<body>
<input type=button onclick="tab()" value="create">
<div id="tab"></div>
</body>
Even though this will remove the undefined from the page, I strongly recommend you to consider more clean, optimized tab function.
function tab()
{
var x=4;
var table = document.createElement('table');
table.id="a-table";
for (var i = 0; i < x; i++){
var tr = document.createElement('tr');
tr.id="myrow";
var td1 = document.createElement('td');
var td2 = document.createElement('td');
tr.appendChild(td1);
tr.appendChild(td2);
table.appendChild(tr);
}
document.getElementById("tab").appendChild(table);
var cells = document.getElementById("a-table").getElementsByTagName("td");
var i=0;
for(i = 0; i < x+1; i++){
var cell = cells[i];
cell.innerHTML = "<img class=img1 src=faculty/comm/"+i+".jpg>";
}
}
td {
border: solid 1px #000;
border-style: none solid solid none;
padding: 10px;
border-radius:8px;
}
<input type=button onclick="tab()" value="create">
<div id="tab"></div>