Datepicker in Javascript - 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>

Related

Edit table Javascript and corresponding dates

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 :(

Filter response from api and show them in different div on the basis of points

I want to sort them on the basis of points. I suppose the points id less than 100 then it should be appended to a <div class="small"> div and if it is higher then 100 and it should be appended to another div.
Right now the whole data is showing in the same div. How do I filter them so can be shown in different div according to the points they have.
Code
function getLeaderbordDetail()
{
var html_data= '';
myMemberId = NextBee.NBUtil.getSession(advertiserId + '_memberId');
var selector = {
'leaderBoardCont': $('#leaderBoard-cont')
},
noDataHtml = '<center><span class="no-leader">No Data Found!</span></center>',
getRowFn = function (srNo, point, firstName, lastName, schoolName) {
var htm = '';
var schoolLogo = '';
if (schoolName == null || schoolName == "")
{
var schoolLogo = '<div style="background: url(https:...../img/avatar.png)" class="profile-pic-circle" />';
}
else
{
var schoolLogo = getLogoPath(schoolName);
}
htm += '<div class="lb-user">'
htm += '<div class="row">'
htm += '<div class="col-sm-4 col-xs-12">'
htm += '<div class="lb-nummber"><span>' + srNo + '</span> ' + schoolLogo + '</div>'
htm += '</div>'
htm += '<div class="col-sm-8 col-xs-12">'
htm += '<div class="lb-desc">'
htm += '<h4>' + firstName + '</h4>'
htm += '<p>' + point + ' Points</p>'
htm += '</div>'
htm += '</div>'
htm += '</div>'
htm += '</div>'
return htm;
};
var currentTime = new Date();
var year = currentTime.getFullYear();
var firstDay = year + "-" + "01" + "-" + "01";
var lastDay = year + "-" + "12" + "-" + "31";
api.getRealTimLeaderBoardByType({
'member_program_id': programId,
'limit': 10,
'type': 'points',
'startDate':firstDay,
'endDate':lastDay
}, function (res1) {
var htm = '', leaderBoardData, leaderBoarddataCnt = 0, srNo;
if (typeof res1.status !== 'undefined') {
switch (res1.status) {
case 'success':
leaderBoardData = res1.response.leader_board;
for (var idx in leaderBoardData) {
srNo = leaderBoarddataCnt + 1;
if (leaderBoardData[idx]['memberInfo']['first_name'] == null)
leaderBoardData[idx]['memberInfo']['first_name'] = "--";
if (leaderBoardData[idx]['memberInfo']['last_name'] == null)
leaderBoardData[idx]['memberInfo']['last_name'] = "--";
if($.inArray(leaderBoardData[idx].member_id,['4482435','4483316','4482441'])==-1){
htm += getRowFn(srNo, leaderBoardData[idx]['point_count'], leaderBoardData[idx]['memberInfo']['first_name'], leaderBoardData[idx]['memberInfo']['last_name'], leaderBoardData[idx]['memberInfo']['profile_phto_url']);
leaderBoarddataCnt++;
}
if (leaderBoardData[idx]['member_id'] == myMemberId) {
myMemberId = "";
}
}
break;
default:
htm = noDataHtml;
break;
}
}
else
{
htm = noDataHtml;
}
selector.leaderBoardCont.html(htm);
var lbd_length = leaderBoardData.length
console.log(lbd_length);
if(lbd_length < 10 ) {
html_data += '<div class="lb-user">'
html_data += '<div class="row">'
html_data += '<div class="col-sm-12 col-xs-12">'
html_data += '<div class="">BECOME A <span class="bold">DVD CREW</span> TO SEE YOUR NAME HERE!</div>'
html_data += '</div>'
html_data += '</div>'
html_data += '</div>'
$("#leaderBoard-cont").append(html_data);
// var virtualdiv_length = 10 - lbd_length;
}
});
}
Any help will be greatly appreciated.

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)

Copy Exact Dynamic Table and Values from one JSP to Another

I created a dynamic calendar, which consists of check boxes per day, and this will be populated, the calendar is being constructed when a specific year was selected on the drop-down box. I used JavaScript to construct the HTML table and jQuery's append to display it. My problem is that when this calendar was successfully drawn in the JSP, user will input values check boxes, and clicking a button will redirect to a new JSP (this will be a confirmation screen in where it will reflect the calendar created in the previous JSP, along with the check boxes input.)
Anyone could give me an idea on how to implement this?
My code for constructing the calendar:
// Retrieves the first day of the month (Zero-based.)
function getFirstDay(year, month) {
var firstDate = new Date(year, month, 1)
return firstDate.getDay()
}
// Retrieves the number of days of a specific month.
function getMonthLength(year, month) {
var oneDay = 1000 * 60 * 60 * 24
var thisMonth = new Date(year, month, 1)
var nextMonth = new Date(year, month + 1, 1)
var length = Math.ceil((nextMonth.getTime() - thisMonth
.getTime())
/ oneDay)
return length
}
// Draws the calendar of a specific month in a specific year.
function constructTable(month, year) {
var firstDay = getFirstDay(year, month);
var totalDays = getMonthLength(year, month);
var counter = 1;
var blankCounter = 0;
var done = false;
var months = ["January", "February", "March", "April",
"May", "June", "July", "August", "September",
"October", "November", "December"];
var propertyName = 'selected' + months[month];
var baseline = '<table class="outputTable" summary="Calendar_'
+ months[month]
+ '"><tr><th colspan="7">'
+ months[month]
+ '</th></tr><tr><th>Sun.</th><th>Mon.</th><th>Tue.</th><th>Wed.</th><th>Thu.</th><th>Fri.</th><th>Sat.</th></tr>';
for (var i = 0; i < 6; i++) {
if (i % 2 == 0) {
baseline += '<tr>';
} else {
baseline += '<tr class="gray">';
}
for (var j = 0; j < 7; j++) {
if (i == 0 && blankCounter < firstDay) {
blankCounter++;
baseline += '<td></td>';
continue;
}
if (counter == totalDays) {
done = true;
}
if (counter <= totalDays) {
var index = counter++
switch (j) {
case 0:
baseline += '<td class="daySunday"><input type="checkbox" name="'
+ index
+ '"> '
+ index
+ ' </td>';
break;
case 1:
baseline += '<td class="dayMonday"><input type="checkbox" name="'
+ index
+ '"> '
+ index
+ ' </td>';
break;
case 2:
baseline += '<td class="dayTuesday"><input type="checkbox" name="'
+ index
+ '"> '
+ index
+ ' </td>';
break;
case 3:
baseline += '<td class="dayWednesday"><input type="checkbox" name="'
+ index
+ '"> '
+ index
+ ' </td>';
break;
case 4:
baseline += '<td class="dayThursday"><input type="checkbox" name="'
+ index
+ '"> '
+ index
+ ' </td>';
break;
case 5:
baseline += '<td class="dayFriday"><input type="checkbox" name="'
+ index
+ '"> '
+ index
+ ' </td>';
break;
case 6:
baseline += '<td class="daySaturday"><input type="checkbox" name="'
+ index
+ '"> '
+ index
+ ' </td>';
break;
}
} else {
baseline += '<td></td>';
}
}
baseline += '</tr>';
}
baseline += '</table>';
return baseline;
}

Referencing an array item in a function (as string) javascript

I created an array of strings, with the format "monthX" where is a number that increases throughout the array.
I have a function where I'm trying to reference a specific item of the array, but it keeps coming in as undefined. Here's my code:
function listCategories() {
categoryList.innerHTML = ""
for (var propertyName in categoryObject) {
var rowHTML = "<div>"
rowHTML += "<span class = 'category'>" + categoryObject[propertyName].name + "</span>"
rowHTML += "<span class = '" + monthList[3] + "'><input/></span>"
rowHTML += "</div>"
categoryList.innerHTML += rowHTML
}
}
//Months to load in
for (var i=0; i<24; i++) {
monthList[i] = "month" + (i + startingMonth)
}
The area I'm interested in is that "monthList[3]" line. That keeps coming in as undefined, even though I console.log(monthList[3]) it correctly says "month6". Any ideas? Do I have bug in my code?
Well, two questions:
WHEN do you call "listCategories()" ?
before or after you set monthList?
And, have you set the global for monthList first?
//globalize monthList array to be usable in functions
var monthList;
function listCategories() {
categoryList.innerHTML = ""
for (var propertyName in categoryObject) {
var rowHTML = "<div>"
rowHTML += "<span class = 'category'>" + categoryObject[propertyName].name + "</span>"
rowHTML += "<span class = '" + monthList[3] + "'><input/></span>"
rowHTML += "</div>"
categoryList.innerHTML += rowHTML
}
}
//Months to load in
for (var i=0; i<24; i++) {
monthList[i] = "month" + (i + startingMonth)
}
//do NOT CALL listCategories prior this line!!
That should do
In the code you show us, you never declare monthList or define it as an array.
function listCategories() {
categoryList.innerHTML = ""
for (var propertyName in categoryObject) {
var rowHTML = "<div>"
rowHTML += "<span class = 'category'>" + categoryObject[propertyName].name + "</span>"
rowHTML += "<span class = '" + monthList[3] + "'><input/></span>"
rowHTML += "</div>"
categoryList.innerHTML += rowHTML
}
}
var monthList = [],
startingMonth = 1;
//Months to load in
for (var i=0; i<24; i++) {
monthList[i] = "month" + (i + startingMonth)
}
Notice the additional lines I added after the function definition, but before the loop.

Categories