Edit table Javascript and corresponding dates - javascript

I have this table:
I'm trying to insert the events I have in my database in a certain way: basically what i would like is to let the code to check the name of the events in my database (blue square) and associate the cells (above the red line) where I add manually my events with the same name. And at that point add the hour difference (between startDate and endDate) in the corresponding day of the month.
This is the code that render the header of my table (where it takes the current month and add every days of that month):
function renderHead(div, start, end) {
var c_year = start.getFullYear();
var r_year = "<tr>";
var daysInYear = 0;
var c_month = start.getMonth();
var r_month = "<tr>";
var daysInMonth = 0;
var r_days = "<tr> <td id= 'event'> Eventi </td>";
for (start; start <= end; start.setDate(start.getDate() + 1)) {
if (start.getFullYear() !== c_year) {
r_year += '<td colspan="' + daysInYear + '">' + c_year + '</td>';
c_year = start.getFullYear();
daysInYear = 0;
}
daysInYear++;
if (start.getMonth() !== c_month) {
r_month += '<td colspan="' + daysInMonth + '">' + months[c_month] + '</td>';
c_month = start.getMonth();
daysInMonth = 0;
}
daysInMonth++;
r_days += '<td id="days">' + start.getDate() + '</td>';
}
r_days += " <td id='tot'> Totale </td> </tr>";
r_year += '<td colspan="' + (daysInYear) + '">' + months[c_month] + ' '+ c_year +'</td>';
r_year += "</tr>";
table = "<table id='tblData' border='1'>" + r_year + r_days + "</table>";
div.html(table);
}
var date = new Date();
var firstDay = new Date(date.getFullYear(), date.getMonth(), 1);
var lastDay = new Date(date.getFullYear(), date.getMonth() + 1, 0);
renderHead($('div#table2'), new Date(firstDay), new Date(lastDay));
This is the function that get the events (blue square) and the difference between startDate and endDate from my database (and the tbody where i manually add the events):
function getEvents(year, month){
var currentEvents = $('#calendar').fullCalendar('clientEvents').filter(event =\> (new Date(event.start) \> firstDay && new Date(event.end) \<= lastDay));
for(i=0; i\<currentEvents.length; i++) {
if(currentEvents\[i\].nomeUtente == $("#nomeUtente").data('value')){
const start = new Date(currentEvents\[i\].start.\_i);
const end = new Date(currentEvents\[i\].end.\_i);
if (currentEvents\[i\].title == "Normali" || currentEvents\[i\].title == "Ferie"){
const milliseconds = Math.abs((end - start)-5400000);
var hours = milliseconds / 36e5;
}else{
const milliseconds = Math.abs(end - start);
var hours = milliseconds / 36e5;
}
if ($("#tblData tbody").length == 0) {
$("#tblData").append("\<tbody\>"+ "\<tr\>\<td id='norm'\>Normali\</td\>\</tr\>"+
"\<tr\>\<td id='stra'\>Straordinarie\</td\>\</tr\>"+
"\<tr\>\<td id='fer'\>Ferie\</td\>\</tr\>"+
"\<tr\>\<td id='mal'\>Malattia\</td\>\</tr\>"+
"\<tr\>\<td id='perm'\>Permesso\</td\>\</tr\>"+
"\<tr\>\<td id='sm'\>Smart Working\</td\>\</tr\>"+
"\<tr\>\<td id='tras'\>Trasferta\</td\>\</tr\>"+
"\<tr\>\<td id='anr'\>Assenze non retribuita\</td\>\</tr\>"+
"\<tr\>\<td id='alt'\>Altro\</td\>\</tr\>"+ "\</tbody\>");
}
$("#tblData tbody").append("\<tr\>" +
//"\<td\>" + currentEvents\[i\].title + "\</td\>" +
"\<td\>" + hours + "\</td\>" +
"\<td\>" + hours + "\</td\>" +
"\<td\>" + hours + "\</td\>" +
"\<td\>" + hours + "\</td\>" +
"\<td\>" + hours + "\</td\>" +
"\<td\>" + hours + "\</td\>" +
"\<td\>" + hours + "\</td\>" +
"\<td\>" + hours + "\</td\>" +
"\<td\>" + hours + "\</td\>" +
"\<td\>" + hours + "\</td\>" +
"\<td\>" + hours + "\</td\>" +
"\<td\>" + hours + "\</td\>" +
"\<td\>" + hours + "\</td\>" +
"\<td\>" + hours + "\</td\>" +
"\</tr\>");
}
}
};
For reference, this is my database:
This is what I've been doing so far:
function getEvents(year, month){
var table = document.getElementById('tblData');
var currentEvents = $('#calendar').fullCalendar('clientEvents').filter(event => (new Date(event.start) > firstDay && new Date(event.end) <= lastDay));
for(i=0; i<currentEvents.length; i++) {
if(currentEvents[i].nomeUtente == $("#nomeUtente").data('value')){
const start = new Date(currentEvents[i].start._i);
const end = new Date(currentEvents[i].end._i);
if (currentEvents[i].title == "Normali" || currentEvents[i].title == "Ferie"){ //provato a mettere una condizione nel quale se Normali o Ferie togliere millisecondi se no no
const milliseconds = Math.abs((end - start)-5400000);
var hours = milliseconds / 36e5;
}else{
const milliseconds = Math.abs(end - start);
var hours = milliseconds / 36e5;
}
if ($("#tblData tbody").length == 0) {
$("#tblData").append("<tbody>"+ "<tr><td id='norm'>Normali</td></tr>"+
"<tr><td id='stra'>Straordinarie</td></tr>"+
"<tr><td id='fer'>Ferie</td></tr>"+
"<tr><td id='mal'>Malattia</td></tr>"+
"<tr><td id='perm'>Permesso</td></tr>"+
"<tr><td id='sm'>Smart Working</td></tr>"+
"<tr><td id='tras'>Trasferta</td></tr>"+
"<tr><td id='anr'>Assenze non retribuita</td></tr>"+
"<tr><td id='alt'>Altro</td></tr>"+ "</tbody>");
}
for (var r = 0, n = table.rows.length; r < n; r++) {
for (var c = 0, m = table.rows[r].cells.length; c < m; c++) {
if(table.rows[r].cells[c].innerHTML == currentEvents[i].title){ //controlla contenuto cella se è uguale ad evento
$("#tblData tbody #days").append("<tr> <td>" + hours + "</td></tr>");
}else{
alert (table.rows[r].cells[c].innerHTML);
}
}
}
}
}
};
But it doesnt work :(

Related

How to get time in select box with half hour interval in jquery

I am not getting 23:30 in option of select box. Can anybody tell me the correct way to add with 30 minute interval in option.
jQuery(document).ready(function() {
var hr = "00";
var mi = "00";
var count = 0;
for (hr = "0"; hr < 24; hr++) {
if (hr < 10) {
apd = "0";
} else {
apd = ""
}
if (count % 2 == 0) {
mi = "00";
jQuery("#bmg_monday_start_hour").append('<option val="' + apd + hr + ':' + mi + '">' + apd + hr + ':' + mi + '</option>');
} else {
hr--;
mi = "30";
jQuery("#bmg_monday_start_hour").append('<option val="' + apd + hr + ':' + mi + '">' + apd + hr + ':' + mi + '</option>')
}
count++;
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
<select name="bmg_monday_start_hour" id="bmg_monday_start_hour" class="form-control bmg-hrs-mins-input"></select>
</div>
You could remove the logic around count.
e.g.
let $select = jQuery("#bmg_monday_start_hour");
for (let hr = 0; hr < 24; hr++) {
let hrStr = hr.toString().padStart(2, "0") + ":";
let val = hrStr + "00";
$select.append('<option val="' + val + '">' + val + '</option>');
val = hrStr + "30";
$select.append('<option val="' + val + '">' + val + '</option>')
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
<select name="bmg_monday_start_hour" id="bmg_monday_start_hour" class="form-control bmg-hrs-mins-input"></select>
</div>
you can achive that in few lines using array of hr and array of mi looping through hr array and append option
$(document).ready(function() {
var hr=['00','01','02','03','04','05','06','07','08','09','10','11','12','13','14','15','16','17','18','19','20','21','22','23'];
var mi=['00','30'];
for( i=0;i<hr.length;i++){
$("#bmg_monday_start_hour").append('<option val="' + hr[i] + ':' + mi[0] + '">'+ hr[i] + ':' + mi[0] + '</option>');
$("#bmg_monday_start_hour").append('<option val="' + hr[i] + ':' + mi[1] + '">' + hr[i] + ':' + mi[1] + '</option>');
}
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
<select name="bmg_monday_start_hour" id="bmg_monday_start_hour" class="form-control bmg-hrs-mins-input">
</select>
</div>
jQuery(document).ready(function () {
var hr = "00";
var mi = "00";
var count = 0;
var apd = "0";
for (hr = "0"; hr <= 24; hr++) {
if (hr <= 10) {
apd = "0";
} else {
apd = "";
}
if (count % 2 == 0) {
mi = "00";
if (hr != "24" && hr != "10") {
jQuery("#bmg_monday_start_hour").append('<option val="' + apd + hr + ':' + mi + '">' + apd + hr + ':' + mi + '</option>');
}
else if (hr == "10") {
jQuery("#bmg_monday_start_hour").append('<option val="' + hr + ':' + mi + '">' + hr + ':' + mi + '</option>');
}
} else {
hr--;
mi = "30";
jQuery("#bmg_monday_start_hour").append('<option val="' + apd + hr + ':' + mi + '">' + apd + hr + ':' + mi + '</option>')
}
count++;
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
<select name="bmg_monday_start_hour" id="bmg_monday_start_hour" class="form-control bmg-hrs-mins-input"></select>
</div>
Well
for(hr = "0"; hr < 24; hr++) {
// Lets say hr == 23 here, and following condition is true (thus adding 23:00)
if(count%2==0) {
// ...
}
}
Then next iteration will do hr++, which isn't less than 24 anymore.
Much cleaner solution will be
for(hr = "0"; hr < 24; hr++) {
if(hr < 10) {
apd = "0";
} else {
apd = ""
}
mi = "00";
jQuery("#bmg_monday_start_hour").append('<option val="' + apd + hr + ':' + mi + '">' + apd + hr + ':' + mi + '</option>');
mi = "30";
jQuery("#bmg_monday_start_hour").append('<option val="' + apd + hr + ':' + mi + '">' + apd + hr + ':' + mi + '</option>');
}

How to fire the javascript function in the textboxes that are getting created dynamically in asp .net

Below is my code which creates the textboxes dynamically in modal pop up each time when i click add button and removes the text boxes in that row each time when i click remove button which is working fine till here the problem is i have the javascript function which validates the month date and year in text box that if if we give any number greater than 12 it shows message that month should be less than 12 similarly for date also it will accept till 31 but if it is greater than 31 it shows error message and similarly year also but this is done for our asp text boxes how can i make this javascript function to work in modal pop where the textboxes are created dynamically
<script type="text/javascript">
function GetDynamicTextBox(value) {
if (value == "") {
FillDropdown()
return '<input name = "DynamicTextBox" value = "' + value + '" placeholder="MM/DD/YYYY"></input> <select name = "DynamicTextBox" >"' + Hours + '"</Select><b>:</b><select name = "DynamicTextBox">"' + Min + '"</Select>' +
' <input id="btnAdd123" type="button" value="Add" onclick="AddTextBox()" /><input type="button" value="Remove" onclick = "RemoveTextBox(this)" />'
//Min = "";
// Hours = "";
//
}
}
var HHEdit = "";
var MMEdit = "";
function GetDynamicTextBox1(value) {
values = value.split(' ');
one = values[0];
two = values[1];
values = two.split(':');
three = values[0];
Four = values[1];
HHEdit = three;
MMEdit = Four;
FillDropdown()
return '<input name = "DynamicTextBox" value = "' + one + '" placeholder="MM/DD/YYYY"></input> <select name = "DynamicTextBox" >"' + Hours + '"</Select><b>:</b><select name = "DynamicTextBox">"' + Min + '"</Select>' +
' <input id="btnAdd123" type="button" value="Add" onclick="AddTextBox()" /><input type="button" value="Remove" onclick = "RemoveTextBox(this)" />'
// $('.DynamicTextBox').val(one);
}
function AddTextBox() {
var div = document.createElement('DIV');
div.innerHTML = GetDynamicTextBox("");
document.getElementById("TextBoxContainer").appendChild(div);
}
function AddTextBox1() {
var inputCount = document.getElementById('TextBoxContainer').getElementsByTagName('input').length;
if (inputCount == "0") {
var div = document.createElement('DIV');
div.innerHTML = GetDynamicTextBox("");
document.getElementById("TextBoxContainer").appendChild(div);
}
}
function RemoveTextBox(div) {
document.getElementById("TextBoxContainer").removeChild(div.parentNode);
}
function RecreateDynamicTextboxes() {
var values = eval('<%=Values%>');
if (values != null) {
var html = "";
for (var i = 0; i < values.length; i++) {
html += "<div>" + GetDynamicTextBox1(values[i]) + "</div>";
}
document.getElementById("TextBoxContainer").innerHTML = html;
}
}
var Hours = "";
var Min = "";
function FillDropdown() {
for (var i = 0; i < 24; i++) {
if (i >= 0 && i <= 9) {
if (HHEdit != "" && HHEdit == i) {
Hours += '<option value="' + i + '" selected="selected">' + " 0" + i + " " + '</option>'
}
else {
Hours += '<option value="' + i + '">' + " 0" + i + " " + '</option>';
}
}
else {
if (HHEdit != "" && HHEdit == i) {
Hours += '<option value="' + i + '" selected="selected">' + " " + i + " " + '</option>';
}
else {
Hours += '<option value="' + i + '">' + " " + i + " " + '</option>';
}
}
}
for (var i = 0; i < 60; i++) {
if (i >= 0 && i <= 9) {
if (MMEdit != "" && MMEdit == i) {
Min += '<option value="' + i + '" selected="selected">' + " 0" + i + " " + '</option>';
}
else {
Min += '<option value="' + i + '">' + " 0" + i + " " + '</option>';
}
}
else {
if (MMEdit != "" && MMEdit == i) {
Min += '<option value="' + i + '" selected="selected">' + " " + i + " " + '</option>';
}
else {
Min += '<option value="' + i + '">' + " " + i + " " + '</option>';
}
}
}
//$('#Item').append(option);
}
window.onload = RecreateDynamicTextboxes;
</script>
Code for date month year validation using javascript
var fdate = document.getElementById('<%=txtFromDate.ClientID%>').value;
var tdate = document.getElementById('<%=txtToDate.ClientID%>').value;
var fromdate = fdate.split('/');
var fmonth = fromdate[0];
var fdate = fromdate[1];
var fyear = fromdate[2];
if (fmonth > 12) {
message += "From Month Should Be Less Than 12." + "\n";
}
if (fdate > 31) {
message += "From Date Cannot Be Greater Than 31." + "\n";
}
if (fyear < 2000 || fyear > 2030) {
message += "From Year Should Be In Between 2000 to 2030." + "\n";
}
var todate = tdate.split('/');
var tmonth = todate[0];
var tdate = todate[1];
var tyear = todate[2];
if (tmonth > 12) {
message += "To Month Should Be Less Than 12." + "\n";
}
if (tdate > 31) {
message += "To Date Cannot Be Greater Than 31." + "\n";
}
if (tyear < 2000 || tyear > 2030) {
message += "To Year Should Be In Between 2000 to 2030."+"\n";
}
if (message != "") {
alert(message);
return false;
}
From Date: <asp:TextBox ID="txtFromDate" Width="113px" runat="server" placeholder="mm/dd/yyyy" onkeypress="return IsValidData(event);" ondrop="return false;"
onpaste="return false;" onkeyup="this.value=this.value.replace(/^(\d\d)(\d)$/g,'$1/$2').replace(/^(\d\d\/\d\d)(\d+)$/g,'$1/$2').replace(/[^\d\/]/g,'')"></asp:TextBox> <span id="error" style="color: Red; display: none">* Invalid Character</span>
To Date: <asp:TextBox ID="txtToDate" Width="113px" runat="server" placeholder="mm/dd/yyyy" onkeypress="return IsValidData(event);" ondrop="return false;"
onpaste="return false;" onkeyup="this.value=this.value.replace(/^(\d\d)(\d)$/g,'$1/$2').replace(/^(\d\d\/\d\d)(\d+)$/g,'$1/$2').replace(/[^\d\/]/g,'')"></asp:TextBox><span id="Span1" style="color: Red; display: none">* Invalid Character</span>
I don't see that you've actually defined your IsValidData function. I'm assuming that you've done that somewhere...
You can pass this to your IsValidData function as a parameter to work with the element that triggered the event in your function..
Also you should try moving away from inline functions to event listeners. This stack post (JavaScript click event listener on class) talks about applying an event listener to a class of DOM elements.
If you are using jQuery, since you included this tag, then I'd encourage you to look into the jQuery .on() function to add event handlers. It'll make everything much easier (http://api.jquery.com/on/)
If you do not know what a javascript event listener is, then start here (https://www.w3schools.com/js/js_htmldom_eventlistener.asp)

Historical data in array - yql

I have this script to get the historical data from last year to today. The script is running good with one stock (in this example "mo"). I build an array because I want 6 stocks and the loop needs to build 6 tables. If I replace the stock name "mo" with my array name I get error.
var yyyy = new Date().getFullYear();
var mm = new Date().getMonth() + 1;
if (mm < 10) {
mm = "0" + mm;
}
var dd = new Date().getDate();
var endDate = yyyy + "-" + mm + "-" + dd;
var startDate = (yyyy - 1) + "-" + mm + "-" + dd;
$.ajax({
url: "https://query.yahooapis.com/v1/public/yql?q=select * from yahoo.finance.historicaldata where symbol = 'mo' and startDate = '" + startDate + "' and endDate = '" + endDate + "'&format=json&diagnostics=true&env=store://datatables.org/alltableswithkeys&callback=",
dataType: 'json',
success: function (data) {
var myTable = "";
myTable += "<br /><table border='1' cellpadding='0' cellspacing='0' width='500' bgcolor='green'>";
myTable += "<tr>";
myTable += "<td>Date</td><td>Open</td><td>Low</td><td>High</td><td>Volume</td><td>Close Price</td>";
myTable += "</tr>";
$.each(data.query.results.quote, function (index, item) {
myTable += "<tr><td>" + item.Date + "</td><td>" + item.Open + "</td><td>" + item.Low + "</td><td>" + item.High + "</td><td>" + item.Volume + "</td><td>" + item.Close + "</td></tr>";
});
myTable += "</table>";
$("#quotes").html(myTable);
},
error: function () {
$("#quotes").html('<p>Something has gone terribly wrong.</p>');
}
});
You don't need to build 6 table queries. You can use the "IN" keyword. Sample query if you want historical data for "YHOO", "GOOG" and "AAPL" stock
select * from yahoo.finance.historicaldata where symbol IN ("YHOO","GOOG","AAPL") and startDate = "2009-09-11" and endDate = "2010-03-10"
Test it out in YQL console here

Why is the output being overwritten for this javascript

Expanded a previous question and it is working fine with the exception to the daily output. As the user enters each week/daily intake of supplement packs it should display to screen until the number of days entered is met. If a user input 2 weeks and 3 days (number of days packs were taken each week) the output should look like:
Week 1
Number of packs taken on Day 1 = 2
Number of packs taken on Day 2 = 1
Number of packs taken on Day 3 = 3
Week 2
Number of packs taken on Day 1 = 1 etc....
My code keeps writing over Week 1. I'm sure this is something simple that I overlooked. Maybe a variable to hold each weeks input? My code thus far...thanks for the help.
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Daily Supplement Intake Log</title>
<script>
function getSup() {
var numWeeks = parseInt(document.getElementById("week").value);
var daysPerWeek = parseInt(document.getElementById("day").value);
var sum = 0;
var i = 0;
var total = 0;
while(i < numWeeks) {
var d = 0;
var grandTotal = 0;
var maxPacks = 0;
var highDay = 0;
while(d < daysPerWeek){
var packsTaken = prompt("Enter the number of packs taken on week " + (i + 1) + " and day "+ (d + 1), "");
total = parseInt(packsTaken);
document.getElementById("output2").innerHTML+="Number of packs for day " + (d + 1) + " = " + total + "<br />";
if(packsTaken > maxPacks){
maxPacks = packsTaken;
highDay = d;
}
sum += total;
d++;
}
grandTotal += sum;
i++;
document.getElementById("output1").innerHTML="Week " + i + "<br />";
document.getElementById("output3").innerHTML="Week " + i + "
subtotal is " + sum + " supplement packs." + "<br>"
+ "Week " + i + " largest day is " + maxPacks + " packs, on day " + d + "<br>";
}
document.getElementById("output4").innerHTML="The total for these weeks
is " + grandTotal + " supplement packs." + "<br>";
}
</script>
<body>
<header><h1>Daily Supplement Packet Log</h1></header><br>
<section>
<div class="align">
<label>Number of weeks:</label>
<input type="text" name="textbox" id="week" value=""><br>
<label>Number of days per week:</label>
<input type="text" name="textbox" id="day" value=""><br></div>
<div id="button">
<button type="button" id="log" onclick="getSup()">Enter number of packs
taken each day</button></div>
</section>
<div id="output1"></div>
<div id="output2"></div>
<div id="output3"></div>
<div id="output4"></div>
</body>
</html>
Using document.createElement method to dynamically create and order output divs. JSFiddle demo.
First replace your <div id="output1"></div>, ...2, ...3, and ...4 divs with:
<div id="outputs"></div>
<div id="total"></div>
...and then swap your getSup function with this:
function getSup() {
var numWeeks = parseInt(document.getElementById("week").value);
var daysPerWeek = parseInt(document.getElementById("day").value);
var sum = 0;
var i = 0;
var total = 0;
var d = 0;
var grandTotal = 0;
var maxPacks = 0;
var highDay = 0;
var packsTaken;
var tempDiv, weekListText
var outputs = document.getElementById("outputs");
while(i < numWeeks) {
d = 0;
grandTotal = 0;
maxPacks = 0;
highDay = 0;
weekListText = '';
while(d < daysPerWeek){
packsTaken = prompt("Enter the number of packs taken on week " + (i + 1) + " and day "+ (d + 1), "");
total = parseInt(packsTaken);
//document.getElementById("output2").innerHTML+="Number of packs for day " + (d + 1) + " = " + total + "<br />";
weekListText += "Number of packs for day " + (d + 1) + " = " + total + "<br />";
if(packsTaken > maxPacks){
maxPacks = packsTaken;
highDay = d;
}
sum += total;
d++;
}
grandTotal += sum;
i++;
//document.getElementById("output1").innerHTML="Week " + i + "<br />";
tempDiv = document.createElement('div');
tempDiv.innerHTML = "Week " + i;
outputs.appendChild(tempDiv);
// formerly known as output2
tempDiv = document.createElement('div');
tempDiv.innerHTML = weekListText;
outputs.appendChild(tempDiv);
//document.getElementById("output3").innerHTML="Week " + i + "subtotal is " + sum + " supplement packs." + "<br>" + "Week " + i + " largest day is " + maxPacks + " packs, on day " + d + "<br>";
tempDiv = document.createElement('div');
tempDiv.innerHTML = "Week " + i + "subtotal is " + sum + " supplement packs." + "<br>" + "Week " + i + " largest day is " + maxPacks + " packs, on day " + d + "<br>";
outputs.appendChild(tempDiv);
}
document.getElementById("total").innerHTML="The total for these weeks is " + grandTotal + " supplement packs." + "<br>";
}
This is mostly the same as the original, but I've rem'ed out the old innerHTML assignments and moved the vars up to the top of the function to reflect actual variable scope.
You overwrite the html, you do not append to it like you do in the loop.
document.getElementById("output1").innerHTML="Week " + i + "<br />";
document.getElementById("output3").innerHTML="Week " + i + "
should be
document.getElementById("output1").innerHTML += "Week " + i + "<br />";
document.getElementById("output3").innerHTML += "Week " + i + ";
but that is not going to make the output you want since they are the same sections. You really should be appending new elements to the page.
var header = document.createElement("h2");
header.innerHTML = "Week " + i;
document.getElementById("output1").appendChild(header);
var div = document.createElement("div");
div.innerHTML = "new content";
document.getElementById("output1").appendChild(div);

Datepicker in Javascript

What is the best way(pattern) to Create datepicker in Javascript.
I have created one using Singleton pattern, but am not satisfied.
You can just use jQuery UI Datepicker and forget about it.
1) Singleton Pattern
The Singleton pattern is often known as an "anti pattern", in other words only use it if absolutely necessary.
Is there a really good reason for all your calendars to use the same instance? I would guess not.
2) Javascript datepickers
I would recommend looking around for date picker libraries, or use jQuery.
I am a fan of http://jonathanleighton.com/projects/date-input (jQuery)
Lightweight and simple! :-)
CIC Kalender skript.
<script language="JavaScript" src="kalender.js"></script>
<script language="JavaScript">
var Singleton = new function Singleton()
{
var instance = this;
var count = 0;
var result = "";
var callBack = "";
var id = "vnd";
var d = new Date();
var days = new Array('So','Mo','Di','Mi','Do','Fr','Sa');
var months = new Array('Januar', 'Februar','März','April','Mai','Juni','Juli','August','September','Oktober','November','Dezember');
var month = d.getMonth();
var date = d.getDate();
var day = d.getDay();
d.setDate(1);
var firstDay = d.getDay();
d.setDate(date);
var year = d.getFullYear();
Singleton.getInstance = function()
{
return instance;
}
this.toString = function()
{
return "[object Singleton]";
}
this.instanceMethod = function()
{
alert( "instance method called!" );
}
this.setCallBack = function(callBackFuncName) {
callBack = callBackFuncName;
}
this.getFormattedDate = function() {
return date + '.' + month + '.' + year;
}
this.getLength = function() {
switch(month){
case 1:
if ((year%4==0 &&
year%100!=0) ||
year%400==0)
return 29; // leap year
else
return 28;
case 3:
return 30;
case 5:
return 30;
case 8:
return 30;
case 10:
return 30
default:
return 31;
}
}
this.setDateVariable = function() {
day = d.getDay();
month = d.getMonth();
d.setDate(1);
firstDay = d.getDay();
d.setDate(date);
year = d.getFullYear();
}
this.writeCalendar = function() {
var calString = '<div id="calContainer" >';
calString += '<table id="cal' + id + '" cellspacing="0" width="200"' + ' style="border:1px black solid;">';
calString += '<tr><th colspan="7" class="month">' + months[month] + ' ' + year + '</th></tr>';
/*
* Row containing days of the week.
*/
calString += '<tr>';
for( var i = 0; i < days.length; i++ ) {
calString += '<th class="dayHeader">' + days[i] + '</th>';
}
calString += '</tr>';
/*
* Body of the Calendar.
*/
calString += '<tr>';
for(var j = 0; j < 42; j++ ) {
var displayNum = (j-firstDay+1);
if( j < firstDay ) {
calString += '<td class="empty"></td>';
} else if ( displayNum == date ) {
calString += '<td id="' + id +
'selected" class="date" ' +
'onClick="Singleton.getInstance().changeDate(this,\'' +
id + '\')">' + displayNum + '</td>';
} else if ( displayNum > length ) {
calString += '<td> </td>';
} else if(displayNum <= date) {
calString += '<td id="" class="days" ' +
id + '\')">' + displayNum + '</td>';
}
else {
calString += '<td id="" class="days" ' +
'onClick="Singleton.getInstance().changeDate(this,\'' +
id + '\')">' + displayNum + '</td>';
}
if(j%7==6){
calString += '</tr><tr>';
}
}
/*
* close the last number row
*/
calString += '</tr>';
/*
* the nav row
*/
calString += '<tr>';
calString += '<td class="nav" ' +
'style="text-decoration:underline;"' +
' onClick="Singleton.getInstance().changeMonth(-12,\'' + id +
'\')"><</td>';
calString += '<td class="nav" ' +
'onClick="Singleton.getInstance().changeMonth(-1,\'' + id +
'\')"><</td>';
calString += '<td class="month" ' +
'colspan="3"> </td>';
calString += '<td class="nav"' +
' onClick="Singleton.getInstance().changeMonth(1,\'' + id +
'\')">></td>';
calString += '<td class="nav" ' +
'style="text-decoration:underline;text-' +
'align:right;" onClick="Singleton.getInstance().changeMonth(12,\'' +
id + '\')">></td>';
calString += '</tr>';
calString += '</table>';
calString += '</div>';
result = calString;
return calString;
}
this.changeDate = function(td) {
var oDiv = document.getElementById(id + "selected");
oDiv.className = "days";
oDiv.id = "";
td.className = id + "selected";
td.id = id + "selected";
date = parseInt(td.innerHTML);
// Create new Date object.
selected_date = new Date();
selected_date.setDate(date);
selected_date.setMonth(month);
selected_date.setYear(year);
callBack(selected_date);
}
this.changeMonth = function(mo) {
d.setMonth(d.getMonth() + mo);
this.setDateVariable();
document.getElementById("vnd").innerHTML = this.writeCalendar();
}
Singleton.staticMethod = function()
{
count = count+1;
alert( "static method called!" + count);
}
var length = this.getLength();
return Singleton;
}
function init() {
Singleton.getInstance().setCallBack(setDates);
document.getElementById("vnd").innerHTML = Singleton.getInstance().writeCalendar();
}
function setDates(date) {
//alert(date);
}
<div id="vnd" style="font-family: Calibri, Verdana">This is a Date DIV</div>

Categories