Loop through months using javascript - javascript

I have a date texbox to select a date and by using that selected month, I need to loop through the months. For example, if I select today's date I need to showing March as starting month and loop through the months for n number of times. But the problem I am facing here is, after the month of December, I am getting undefined error.
Any idea how to resolve it ?
Fiddle: https://jsfiddle.net/anoopcr/fyaeyg7r/
HTML:
<div class="inputQL">
<div class="InputQuest">Loan start date</div>
<div>
<input type="date" id="date" class="date"></input>
</div>
<div id="hiddendate" class="hiddendate"></div>
</div>
<div id="table_header" class="table_header">
<table cellpadding="15" border="1">
<tr>
<td width="100" align="center"><b>SI No</b></td>
<td width="100" align="center"><b>month</b></td>
<td width="100" align="center"><b>balance</b></td>
</tr>
</table>
</div>
<div id="table" class="table"> </div>
Javascript :
date.onchange = function() {
table();
}
$(document).ready(function() {
document.getElementById("date").valueAsDate = new Date();
table();
})
function table() {
var mo = new Array(12);
mo[0] = "January";
mo[1] = "February";
mo[2] = "March";
mo[3] = "April";
mo[4] = "May";
mo[5] = "June";
mo[6] = "July";
mo[7] = "August";
mo[8] = "September";
mo[9] = "October";
mo[10] = "November";
mo[11] = "December";
var date = new Date(document.getElementById("date").value);
var day = date.getUTCDate();
var month = mo[date.getUTCMonth()];
var year = date.getFullYear();
document.getElementById("hiddendate").innerHTML = month;
var loanstart = month;
var amnttext = 1;
var payment_counter = 1;
var table = "";
table += "<table cellpadding='15' border='1'>";
var n = 0;
while (amnttext < 24) {
var loanstart = mo[date.getUTCMonth() + n];
//display rows
table += "<table cellpadding='15' border='1'>";
table += "<tr>";
table += "<td width='100'>" + payment_counter + "</td>";
table += "<td width='100'>" + loanstart + "</td>";
table += "<td width='100'>" + amnttext + "</td>";
if (n < 12) {
n++;
} else {
n = 0;
}
amnttext++;
payment_counter++;
table += "</table>";
document.getElementById("table").innerHTML = table;
}

One issue is that you access the array mo out of it's limits in
var loanstart = mo[date.getUTCMonth()+n];
Take the modulo by 12 and that Access Violation should be fixed:
var loanstart = mo[(date.getUTCMonth()+n) % 12];
P.S.: As #Vimarsh oberserved, the condition if (n < 12) can be removed completely when using the modulo.

In your code, when n = 11 you increment it rather than making it 0.
Now n = 12 and you get the error as mo[12] is out of bounds.
You can just change the snippet to
if (n<11) {
n++;
} else {
n=0;
}
Although, I agree #milbrandt's answer is a cleaner way to handle this use case.

Related

How to build up a list with html tags in a javascript function

I have written code to display the date (month, day, day nr, and year) with javascript and placed it in a ul.
my question is how to build up a li with html tags (so that i can place breaks) in a javascript function because now if i would for example do the following
var output = "<li>" + month_full[monthFull] + "<br/>" + weekDay[day] + "</li>";
return output;
it will output exactly how its shown -> http://gyazo.com/5a67f3dbd7db07254bd38d58116aac7c
you can horizontally scroll through my months. now i would like to build it up like so: http://gyazo.com/adb760c912691a7ce26b1cc40d89d1df
to check my jsfiddle to see what i have now: https://jsfiddle.net/GY22/vqfk8yLL/2/
my javascript code is the following:
<script>
// Get today's current date.
var now = new Date();
console.log(now);
// Calculates the number of the week
var weekNumber = ((now.getDate()<10) ? "0" : "")+ now.getDate();
console.log("The current week number is: " + weekNumber);
// Array list of months.
var month_full = new Array(12);
month_full[0] = "January";
month_full[1] = "February";
month_full[2] = "March";
month_full[3] = "April";
month_full[4] = "May";
month_full[5] = "June";
month_full[6] = "July";
month_full[7] = "August";
month_full[8] = "September";
month_full[9] = "October";
month_full[10] = "November";
month_full[11] = "December";
//console.log(month[3]);
var weekDay = new Array(7);
weekDay[0]= "Su";
weekDay[1] = "Mo";
weekDay[2] = "Tu";
weekDay[3] = "We";
weekDay[4] = "Th";
weekDay[5] = "Fr";
weekDay[6] = "Sa";
function weekNr_Month(date){
var month = date.getUTCMonth();
return month[month];
}
function formatDate(date) {
var month = date.getUTCMonth() +1;
var dayNumber = date.getUTCDate();
var year = date.getUTCFullYear();
var day = date.getUTCDay();
var monthFull = date.getUTCMonth();
return month_full[monthFull] + " " + weekDay[day] + ": " + dayNumber + "-" + month + "-" + year + "; ";
}
console.log(formatDate(new Date()));
var today
function addListItem(){
var createListItem = document.createElement("li");
var outputListItem = document.createTextNode(today);
createListItem.appendChild(outputListItem);
var createUl = document.getElementsByTagName("ul");
createUl[0].appendChild(createListItem);
}
// loop starting from may up untill for months from the set date
for (var i = 1; i < 122; i++){
today = formatDate(new Date(2015, 05, i));
//document.write(today + "<br />");
addListItem();
}
document.getElementById('timeline').
getElementsByTagName('li')[(new Date()).getDate() + 1].className += ' currentDate';
</script>
That is because you are creating a text node instead of html content.
Try this:
var createListItem = document.createElement("li");
createListItem.innerHTML = today;

How to clear div content onclick? [duplicate]

This question already has answers here:
How do I clear the content of a div using JavaScript? [closed]
(2 answers)
Closed 7 years ago.
I'm making a calendar purely from Javascript, but when then previous and next months are shown current content is still present. It should replace the div content. Also, current date should be the only one with red font displayed.
<html>
<head><script>
var now = new Date();
var year = now.getFullYear();
var month = now.getMonth();
var monthName = getMonthName(month);
var time = now.toLocaleTimeString();
var date = now.getDate();
now = null;
var calElem = document.getElementById("cal");
function febDays(year) {
if (year % 4 == 0) {
return 29;
} else {
return 28;
}
}
function getDays(month, year) {
var days = new Array(12);
days[0] = 31;
days[1] = febDays(year);
days[2] = 31;
days[3] = 30;
days[4] = 31;
days[5] = 30;
days[6] = 31;
days[7] = 31;
days[8] = 30;
days[9] = 31;
days[10] = 30;
days[11] = 31;
return days[month];
}
function getMonthName(month) {
var mn = new Array(12);
mn[0] = "January";
mn[1] = "February";
mn[2] = "March";
mn[3] = "April";
mn[4] = "May";
mn[5] = "June";
mn[6] = "July";
mn[7] = "August";
mn[8] = "September";
mn[9] = "October";
mn[10] = "November";
mn[11] = "December";
return mn[month];
}
function monthName(month) {
var mn = new Array(12);
mn[0] = "Jan";
mn[1] = "Feb";
mn[2] = "Mar";
mn[3] = "Apr";
mn[4] = "May";
mn[5] = "Jun";
mn[6] = "Jul";
mn[7] = "August";
mn[8] = "September";
mn[9] = "October";
mn[10] = "November";
mn[11] = "December";
return mn[month];
}
function setCal() {
var firstDay = new Date(year, month, 1);
var startDay = firstDay.getDay();
firstDay = null;
var days = getDays(month, year);
drawCal(startDay + 1, days, date, monthName, year, month);
}
function previousMonth() {
document.getElementById('cal').innerHTML = "";
month--;
var monthName = getMonthName(month);
var firstDay = new Date(year, month, 1);
var startDay = firstDay.getDay();
firstDay = null;
var days = getDays(month, year);
drawCal(startDay + 1, days, date, monthName, year, month);
if (monthName === "January"){
year--;
month = 11;
monthName = getMonthName(month);
firstDay = new Date(year, month, 1);
startDay = firstDay.getDay();
firstDay = null;
days = getDays(month, year);
drawCal(startDay + 1, days, date, monthName, year, month);
}
}
function nextMonth() {
document.getElementById('cal').innerHTML = "";
month++;
var monthName = getMonthName(month);
var firstDay = new Date(year, month, 1);
var startDay = firstDay.getDay();
firstDay = null;
var days = getDays(month, year);
drawCal(startDay + 1, days, date, monthName, year, month);
if (monthName === "December"){
year++;
month = 0;
monthName = getMonthName(month);
firstDay = new Date(year, month, 1);
startDay = firstDay.getDay();
firstDay = null;
days = getDays(month, year);
drawCal(startDay + 1, days, date, monthName, year, month);
}
}
function drawCal(startDay, lastDate, date, monthName, year, month) {
var headerHeight = 50;
var border = 2;
var cellspacing = 4;
var headerSize = "+3";
var colWidth = 60;
var dayCellHeight = 25;
var cellHeight = 40;
var todayColor = "red";
var text = "";
text += '<div id="cal">';
text += '<TABLE BORDER=' + border + ' CELLSPACING=' + cellspacing + '>';
text += '<TH COLSPAN=7 HEIGHT=' + headerHeight + '>';
text += '<FONT SIZE=' + headerSize + '>';
text += monthName + ' ' + year;
text += '</FONT>';
text += '</TH>';
var openCol = '<TD WIDTH=' + colWidth + ' HEIGHT=' + dayCellHeight + '>';
var closeCol = '</TD>';
var weekDay = new Array(7);
weekDay[0] = "Sunday";
weekDay[1] = "Monday";
weekDay[2] = "Tuesday";
weekDay[3] = "Wednesday";
weekDay[4] = "Thursday";
weekDay[5] = "Friday";
weekDay[6] = "Saturday";
text += '<TR ALIGN="center" VALIGN="center">';
for (var dayNum = 0; dayNum < 7; ++dayNum) {
text += openCol + weekDay[dayNum] + closeCol;
}
text += '</TR>';
var digit = 1;
var curCell = 1;
for (var row = 1; row <= Math.ceil((lastDate + startDay - 1) / 7); ++row) {
text += '<TR ALIGN="right" VALIGN="top">';
for (var col = 1; col <= 7; ++col) {
if (digit > lastDate)
break;
if (curCell < startDay) {
text += '<TD></TD>';
curCell++;
} else {
if (digit == date) {
text += '<TD HEIGHT=' + cellHeight + '>';
text += '<FONT COLOR="' + todayColor + '">';
text += digit + " ";
text += '</FONT>';
text += '</TD>';
} else
text += '<TD HEIGHT=' + cellHeight + '>' + digit + '</TD>';
digit++;
}
}
text += '</TR>';
}
text += '</TABLE>';
text += '</CENTER>';
text += '</div>';
text += '<button onclick="previousMonth()"><</button>';
text += '<button onclick="nextMonth()">></button>';
document.write(text);
}
</script></head>
<body onload="setCal()">
</body>
</html>
I think it will be better if you can use a container element and set its content rather than to use document.write()
<html>
<head><script>
var now = new Date();
var year = now.getFullYear();
var month = now.getMonth();
var monthName = getMonthName(month);
var time = now.toLocaleTimeString();
var date = now.getDate();
now = null;
var calElem = document.getElementById("cal");
function febDays(year) {
if (year % 4 == 0) {
return 29;
} else {
return 28;
}
}
function getDays(month, year) {
var days = new Array(12);
days[0] = 31;
days[1] = febDays(year);
days[2] = 31;
days[3] = 30;
days[4] = 31;
days[5] = 30;
days[6] = 31;
days[7] = 31;
days[8] = 30;
days[9] = 31;
days[10] = 30;
days[11] = 31;
return days[month];
}
function getMonthName(month) {
var mn = new Array(12);
mn[0] = "January";
mn[1] = "February";
mn[2] = "March";
mn[3] = "April";
mn[4] = "May";
mn[5] = "June";
mn[6] = "July";
mn[7] = "August";
mn[8] = "September";
mn[9] = "October";
mn[10] = "November";
mn[11] = "December";
return mn[month];
}
function monthName(month) {
var mn = new Array(12);
mn[0] = "Jan";
mn[1] = "Feb";
mn[2] = "Mar";
mn[3] = "Apr";
mn[4] = "May";
mn[5] = "Jun";
mn[6] = "Jul";
mn[7] = "August";
mn[8] = "September";
mn[9] = "October";
mn[10] = "November";
mn[11] = "December";
return mn[month];
}
function setCal() {
var firstDay = new Date(year, month, 1);
var startDay = firstDay.getDay();
firstDay = null;
var days = getDays(month, year);
drawCal(startDay + 1, days, date, monthName, year, month);
}
function previousMonth() {
document.getElementById('cal').innerHTML = "";
month--;
var monthName = getMonthName(month);
var firstDay = new Date(year, month, 1);
var startDay = firstDay.getDay();
firstDay = null;
var days = getDays(month, year);
drawCal(startDay + 1, days, date, monthName, year, month);
if (monthName === "January"){
year--;
month = 11;
monthName = getMonthName(month);
firstDay = new Date(year, month, 1);
startDay = firstDay.getDay();
firstDay = null;
days = getDays(month, year);
drawCal(startDay + 1, days, date, monthName, year, month);
}
}
function nextMonth() {
document.getElementById('cal').innerHTML = "";
month++;
var monthName = getMonthName(month);
var firstDay = new Date(year, month, 1);
var startDay = firstDay.getDay();
firstDay = null;
var days = getDays(month, year);
drawCal(startDay + 1, days, date, monthName, year, month);
if (monthName === "December"){
year++;
month = 0;
monthName = getMonthName(month);
firstDay = new Date(year, month, 1);
startDay = firstDay.getDay();
firstDay = null;
days = getDays(month, year);
drawCal(startDay + 1, days, date, monthName, year, month);
}
}
function drawCal(startDay, lastDate, date, monthName, year, month) {
var headerHeight = 50;
var border = 2;
var cellspacing = 4;
var headerSize = "+3";
var colWidth = 60;
var dayCellHeight = 25;
var cellHeight = 40;
var todayColor = "red";
var text = "";
text += '<div id="cal">';
text += '<TABLE BORDER=' + border + ' CELLSPACING=' + cellspacing + '>';
text += '<TH COLSPAN=7 HEIGHT=' + headerHeight + '>';
text += '<FONT SIZE=' + headerSize + '>';
text += monthName + ' ' + year;
text += '</FONT>';
text += '</TH>';
var openCol = '<TD WIDTH=' + colWidth + ' HEIGHT=' + dayCellHeight + '>';
var closeCol = '</TD>';
var weekDay = new Array(7);
weekDay[0] = "Sunday";
weekDay[1] = "Monday";
weekDay[2] = "Tuesday";
weekDay[3] = "Wednesday";
weekDay[4] = "Thursday";
weekDay[5] = "Friday";
weekDay[6] = "Saturday";
text += '<TR ALIGN="center" VALIGN="center">';
for (var dayNum = 0; dayNum < 7; ++dayNum) {
text += openCol + weekDay[dayNum] + closeCol;
}
text += '</TR>';
var digit = 1;
var curCell = 1;
for (var row = 1; row <= Math.ceil((lastDate + startDay - 1) / 7); ++row) {
text += '<TR ALIGN="right" VALIGN="top">';
for (var col = 1; col <= 7; ++col) {
if (digit > lastDate)
break;
if (curCell < startDay) {
text += '<TD></TD>';
curCell++;
} else {
if (digit == date) {
text += '<TD HEIGHT=' + cellHeight + '>';
text += '<FONT COLOR="' + todayColor + '">';
text += digit + " ";
text += '</FONT>';
text += '</TD>';
} else
text += '<TD HEIGHT=' + cellHeight + '>' + digit + '</TD>';
digit++;
}
}
text += '</TR>';
}
text += '</TABLE>';
text += '</CENTER>';
text += '</div>';
text += '<button onclick="previousMonth()"><</button>';
text += '<button onclick="nextMonth()">></button>';
document.getElementById('calc').innerHTML=text;
}
</script></head>
<body onload="setCal()">
<div id="calc"></div>
</body>
</html>
if you want to clear any HTML element you would just
DO NOT use document.write() it clears the whole page.
It's the document.write() It always stays there no matter what. Try not to use document.write()
use createElement('div') instead. It's much more clean, you can keep track of the elements, and they're static, unless you want them to change. everything is under your control.
document.getElementById('Clear_This_Div_id').innerHTML = '';
This will usually clear the element
Without changing much of the other part of your code, you can just change the
document.write(text);
to
document.getElementsByTagName('body')[0].innerHTML = text;
This will clear off the previous content before putting the new one, since you are putting in the body every time.

Cant get what's the issue with Datepicker?

I'm using smarty template engine. I'm using datepicker js plugin. My HTML code is as follows:
<tr>
<td valign="middle" align="right"><b>From Date </b> : </td>
<td align="left" > <input type="text" style="width:100px;" class="inputfield" name="from_date" id="from_date" value="{$from_date}" maxlength="10"/></td>
<td valign="middle" align="right"><b>To Date </b> : </td>
<td> <input type="text" style="width:100px;" class="inputfield" name="to_date" id="to_date" value="{$to_date}" maxlength="10"/></td>
</tr>
The jQuery function code is as below :
{literal}
<script language="javascript" type="application/javascript">
$(function() {
$( "#from_date" ).datepicker({
changeMonth: true,
changeYear: true,
dateFormat: 'dd/mm/yy'
});
});
$(function() {
$( "#to_date" ).datepicker({
changeMonth: true,
changeYear: true,
dateFormat: 'dd/mm/yy'
});
});
$(document).ready(function() {
$("#questions_listing").tablesorter({
widgets:['zebra'],
// sort on the fourth column and first column, order asc
sortList: [[1,0]]
});
});
$(".submit_form").click(function(e) {
var result = validateDate();
if(!result)
return false;
else
document.questions_filter.submit();
});
</script>
{/literal}
The datepicker.js file is as follows:
/* $(function() {
$( "#cal_from_date" ).datepicker({
changeMonth: true,
changeYear: true,
dateFormat: 'dd/mm/yy'
});
$( "#cal_to_date" ).datepicker({
changeMonth: true,
changeYear: true,
dateFormat: 'dd/mm/yy'
});
});*/
var datePickerDivID = "datepicker";
var iFrameDivID = "datepickeriframe";
var dayArrayShort = new Array('Su', 'Mo', 'Tu', 'We', 'Th', 'Fr', 'Sa');
var dayArrayMed = new Array('Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat');
var dayArrayLong = new Array('Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday');
var monthArrayShort = new Array('Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec');
var monthArrayMed = new Array('Jan', 'Feb', 'Mar', 'Apr', 'May', 'June', 'July', 'Aug', 'Sept', 'Oct', 'Nov', 'Dec');
var monthArrayLong = new Array('January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December');
var defaultDateSeparator = "/"; // common values would be "/" or "."
var defaultDateFormat = "dmy" // valid values are "mdy", "dmy", and "ymd"
var dateSeparator = defaultDateSeparator;
var dateFormat = defaultDateFormat;
function displayDatePicker(dateFieldName, displayBelowThisObject, dtFormat, dtSep)
{
var targetDateField = document.getElementsByName (dateFieldName).item(0);
if (!displayBelowThisObject)
displayBelowThisObject = targetDateField;
if (dtSep)
dateSeparator = dtSep;
else
dateSeparator = defaultDateSeparator;
if (dtFormat)
dateFormat = dtFormat;
else
dateFormat = defaultDateFormat;
var x = displayBelowThisObject.offsetLeft;
var y = displayBelowThisObject.offsetTop + displayBelowThisObject.offsetHeight ;
var parent = displayBelowThisObject;
while (parent.offsetParent) {
parent = parent.offsetParent;
x += parent.offsetLeft;
y += parent.offsetTop ;
}
drawDatePicker(targetDateField, x, y);
}
function drawDatePicker(targetDateField, x, y)
{
var dt = getFieldDate(targetDateField.value );
if (!document.getElementById(datePickerDivID)) {
// don't use innerHTML to update the body, because it can cause global variables
// that are currently pointing to objects on the page to have bad references
//document.body.innerHTML += "<div id='" + datePickerDivID + "' class='dpDiv'></div>";
var newNode = document.createElement("div");
newNode.setAttribute("id", datePickerDivID);
newNode.setAttribute("class", "dpDiv");
newNode.setAttribute("style", "visibility: hidden;");
document.body.appendChild(newNode);
}
// move the datepicker div to the proper x,y coordinate and toggle the visiblity
var pickerDiv = document.getElementById(datePickerDivID);
pickerDiv.style.position = "absolute";
pickerDiv.style.left = x + "px";
pickerDiv.style.top = y + "px";
pickerDiv.style.visibility = (pickerDiv.style.visibility == "visible" ? "hidden" : "visible");
pickerDiv.style.display = (pickerDiv.style.display == "block" ? "none" : "block");
pickerDiv.style.zIndex = 10000;
// draw the datepicker table
refreshDatePicker(targetDateField.name, dt.getFullYear(), dt.getMonth(), dt.getDate());
}
function refreshDatePicker(dateFieldName, year, month, day)
{
var thisDay = new Date();
if ((month >= 0) && (year > 0)) {
thisDay = new Date(year, month, 1);
} else {
day = thisDay.getDate();
thisDay.setDate(1);
}
var crlf = "\r\n";
var TABLE = "<table cols=7 class='dpTable'>" + crlf;
var xTABLE = "</table>" + crlf;
var TR = "<tr class='dpTR'>";
var TR_title = "<tr class='dpTitleTR'>";
var TR_days = "<tr class='dpDayTR'>";
var TR_todaybutton = "<tr class='dpTodayButtonTR'>";
var xTR = "</tr>" + crlf;
var TD = "<td class='dpTD' onMouseOut='this.className=\"dpTD\";' onMouseOver=' this.className=\"dpTDHover\";' ";
var TD_title = "<td colspan=5 class='dpTitleTD'>";
var TD_buttons = "<td class='dpButtonTD'>";
var TD_todaybutton = "<td colspan=7 class='dpTodayButtonTD'>";
var TD_days = "<td class='dpDayTD'>";
var TD_selected = "<td class='dpDayHighlightTD' onMouseOut='this.className=\"dpDayHighlightTD\";' onMouseOver='this.className=\"dpTDHover\";' "; // leave this tag open, because we'll be adding an onClick event
var xTD = "</td>" + crlf;
var DIV_title = "<div class='dpTitleText'>";
var DIV_selected = "<div class='dpDayHighlight'>";
var xDIV = "</div>";
// start generating the code for the calendar table
var html = TABLE;
// this is the title bar, which displays the month and the buttons to
// go back to a previous month or forward to the next month
html += TR_title;
html += TD_buttons + getButtonCode(dateFieldName, thisDay, -1, "<") + xTD;
html += TD_title + DIV_title + monthArrayLong[ thisDay.getMonth()] + " " + thisDay.getFullYear() + xDIV + xTD;
html += TD_buttons + getButtonCode(dateFieldName, thisDay, 1, ">") + xTD;
html += xTR;
// this is the row that indicates which day of the week we're on
html += TR_days;
for(i = 0; i < dayArrayShort.length; i++)
html += TD_days + dayArrayShort[i] + xTD;
html += xTR;
// now we'll start populating the table with days of the month
html += TR;
// first, the leading blanks
for (i = 0; i < thisDay.getDay(); i++)
html += TD + " " + xTD;
// now, the days of the month
do {
dayNum = thisDay.getDate();
TD_onclick = " onclick=\"updateDateField('" + dateFieldName + "', '" + getDateString(thisDay) + "');\">";
if (dayNum == day)
html += TD_selected + TD_onclick + DIV_selected + dayNum + xDIV + xTD;
else
html += TD + TD_onclick + dayNum + xTD;
// if this is a Saturday, start a new row
if (thisDay.getDay() == 6)
html += xTR + TR;
// increment the day
thisDay.setDate(thisDay.getDate() + 1);
} while (thisDay.getDate() > 1)
// fill in any trailing blanks
if (thisDay.getDay() > 0) {
for (i = 6; i > thisDay.getDay(); i--)
html += TD + " " + xTD;
}
html += xTR;
// add a button to allow the user to easily return to today, or close the calendar
var today = new Date();
var todayString = "Today is " + dayArrayMed[today.getDay()] + ", " + monthArrayMed[ today.getMonth()] + " " + today.getDate();
html += TR_todaybutton + TD_todaybutton;
html += "<button class='dpTodayButton' onClick='refreshDatePicker(\"" + dateFieldName + "\");'>this month</button> ";
html += "<button class='dpTodayButton' onClick='updateDateField(\"" + dateFieldName + "\");'>close</button>";
html += xTD + xTR;
// and finally, close the table
html += xTABLE;
document.getElementById(datePickerDivID).innerHTML = html;
// add an "iFrame shim" to allow the datepicker to display above selection lists
adjustiFrame();
}
/**
Convenience function for writing the code for the buttons that bring us back or forward
a month.
*/
function getButtonCode(dateFieldName, dateVal, adjust, label)
{
var newMonth = (dateVal.getMonth () + adjust) % 12;
var newYear = dateVal.getFullYear() + parseInt((dateVal.getMonth() + adjust) / 12);
if (newMonth < 0) {
newMonth += 12;
newYear += -1;
}
return "<button class='dpButton' onClick='refreshDatePicker(\"" + dateFieldName + "\", " + newYear + ", " + newMonth + ");'>" + label + "</button>";
}
/**
Convert a JavaScript Date object to a string, based on the dateFormat and dateSeparator
variables at the beginning of this script library.
*/
function getDateString(dateVal)
{
var dayString = "00" + dateVal.getDate();
var monthString = "00" + (dateVal.getMonth()+1);
dayString = dayString.substring(dayString.length - 2);
monthString = monthString.substring(monthString.length - 2);
switch (dateFormat) {
case "dmy" :
return dayString + dateSeparator + monthString + dateSeparator + dateVal.getFullYear();
case "ymd" :
return dateVal.getFullYear() + dateSeparator + monthString + dateSeparator + dayString;
case "mdy" :
default :
return monthString + dateSeparator + dayString + dateSeparator + dateVal.getFullYear();
}
}
/**
Convert a string to a JavaScript Date object.
*/
function getFieldDate(dateString)
{
var dateVal;
var dArray;
var d, m, y;
try {
dArray = splitDateString(dateString);
if (dArray) {
switch (dateFormat) {
case "dmy" :
d = parseInt(dArray[0], 10);
m = parseInt(dArray[1], 10) - 1;
y = parseInt(dArray[2], 10);
break;
case "ymd" :
d = parseInt(dArray[2], 10);
m = parseInt(dArray[1], 10) - 1;
y = parseInt(dArray[0], 10);
break;
case "mdy" :
default :
d = parseInt(dArray[1], 10);
m = parseInt(dArray[0], 10) - 1;
y = parseInt(dArray[2], 10);
break;
}
dateVal = new Date(y, m, d);
} else if (dateString) {
dateVal = new Date(dateString);
} else {
dateVal = new Date();
}
} catch(e) {
dateVal = new Date();
}
return dateVal;
}
function splitDateString(dateString)
{
var dArray;
if (dateString.indexOf("/") >= 0)
dArray = dateString.split("/");
else if (dateString.indexOf(".") >= 0)
dArray = dateString.split(".");
else if (dateString.indexOf("-") >= 0)
dArray = dateString.split("-");
else if (dateString.indexOf("\\") >= 0)
dArray = dateString.split("\\");
else
dArray = false;
return dArray;
}
function updateDateField(dateFieldName, dateString)
{
var targetDateField = document.getElementsByName (dateFieldName).item(0);
if (dateString)
targetDateField.value = dateString;
var pickerDiv = document.getElementById(datePickerDivID);
pickerDiv.style.visibility = "hidden";
pickerDiv.style.display = "none";
adjustiFrame();
targetDateField.focus();
// after the datepicker has closed, optionally run a user-defined function called
// datePickerClosed, passing the field that was just updated as a parameter
// (note that this will only run if the user actually selected a date from the datepicker)
if ((dateString) && (typeof(datePickerClosed) == "function"))
datePickerClosed(targetDateField);
}
function adjustiFrame(pickerDiv, iFrameDiv)
{
// we know that Opera doesn't like something about this, so if we
// think we're using Opera, don't even try
var is_opera = (navigator.userAgent.toLowerCase().indexOf("opera") != -1);
if (is_opera)
return;
// put a try/catch block around the whole thing, just in case
try {
if (!document.getElementById(iFrameDivID)) {
var newNode = document.createElement("iFrame");
newNode.setAttribute("id", iFrameDivID);
newNode.setAttribute("src", "javascript:false;");
newNode.setAttribute("scrolling", "no");
newNode.setAttribute ("frameborder", "0");
document.body.appendChild(newNode);
}
if (!pickerDiv)
pickerDiv = document.getElementById(datePickerDivID);
if (!iFrameDiv)
iFrameDiv = document.getElementById(iFrameDivID);
try {
iFrameDiv.style.position = "absolute";
iFrameDiv.style.width = pickerDiv.offsetWidth;
iFrameDiv.style.height = pickerDiv.offsetHeight ;
iFrameDiv.style.top = pickerDiv.style.top;
iFrameDiv.style.left = pickerDiv.style.left;
iFrameDiv.style.zIndex = pickerDiv.style.zIndex - 1;
iFrameDiv.style.visibility = pickerDiv.style.visibility ;
iFrameDiv.style.display = pickerDiv.style.display;
} catch(e) {
}
} catch (ee) {
}
}
When I tested in firbug it is giving me the error TypeError: $(...).datepicker is not a function
I've included the files reuired i.e. jquery1.9.1 and datepicker .js, but still it's not working. Can anyone help me to resolve this issue?
Your code is just working perfectly! Check out this.
You just missed to include jquery-ui
Try including : <script src="//ajax.googleapis.com/ajax/libs/jqueryui/1.10.3/jquery-ui.min.js"></script> in you <head> tag.
UPDATE: The fiddle is by #Safiuddin

js for loop sort numbers

I have a form where I want people to put in their year of birth. You can only apply if you are over 18 so in the year of birth field I want the min age to be 18. I have done this as shown below however I want to sort the numbers from latest year at the top and oldest year at the bottom. currently I show 1913 first, but I want to show 1994 first. Here is my code
<div id="my-container"></div>
<script>
var d = new Date();
var y = d.getFullYear();
var selectList = "<select>";
for (var x = (y-100); x < (y - 18); x++) {
selectList += "<option>" + x + "</option>";
}
selectList += "</select>";
$('#my-container').html(selectList);
</script>
As Nile mentioned,
var d = new Date();
var y = d.getFullYear();
var selectList = "<select>";
for (var x = y-18; x >= y-100; x--) {
selectList += "<option>" + x + "</option>";
}
selectList += "</select>";
$('#my-container').html(selectList);
http://jsfiddle.net/samliew/WzwKw/
try this
<script>
var d = new Date();
var y = d.getFullYear();
var selectList = "<select>";
for (var x = y-18; x > y - 100; x--) {
selectList += "<option>" + x + "</option>";
}
selectList += "</select>";
$('#my-container').html(selectList);
</script>
<script>
$( document ).ready( function() {
var d = new Date();
var y = d.getFullYear();
var selectList = "<select>";
for (var x = (y-18); x >= (y - 100); x--) {
selectList += "<option>" + x + "</option>";
}
selectList += "</select>";
$('#my-container').html(selectList);
});
</script>
Please try with this.

JavaScript functions only run on first click

After clicking each radio button one time they no longer function properly. I am using onchange in this example. So I set it to only run the function if the element is checked
Javascript
window.addEventListener("load", link_events, false);
var d = new Date();
var month = new Array();
month[0] = "January";
month[1] = "February";
month[2] = "March";
month[3] = "April";
month[4] = "May";
month[5] = "June";
month[6] = "July";
month[7] = "August";
month[8] = "September";
month[9] = "October";
month[10] = "November";
month[11] = "December";
var m = month[d.getMonth()];
var day = d.getDate();
var year = d.getFullYear();
var currentSelected = false;
var specifiedSelected = false;
function link_events(){
document.getElementById("current").onchange = currentDisplay;
document.getElementById("specified").onchange = specifiedDisplay;
}
function currentDisplay(){
if(document.getElementById('current').checked){
var currentDateRow = document.getElementById("currentDateRow");
currentDateRow.innerHTML = currentDateRow.innerHTML + "<td id='currentDate' style='font-family:Verdana;font-size:1.5em;'>" + m + ' ' + day + ', ' + year + "<td>";
document.getElementById("current").checked = true;
var elem = document.getElementById("specifiedDate");
elem.parentNode.removeChild(elem);
}
}
function specifiedDisplay(){
if(document.getElementById('specified').checked){
var specifiedDateRow = document.getElementById('specifiedDateRow');
specifiedDateRow.innerHTML = specifiedDateRow.innerHTML + " <td> <input id='specifiedDate' type='text' class='datepicker'></td>";
document.getElementById("specified").checked = true;
var elem1 = document.getElementById("currentDate");
elem1.parentNode.removeChild(elem1);
}
}
<!DOCTYPE html>
<html>
<head>
<title>BIS 3523 - Assingment 10 - Trivia</title>
<link type="text/css" rel="stylesheet" href="Trivia.css" />
<script src="hw06.js"></script>
<head>
<body style="background-color:gray">
<form>
<table align=center style="margin-top:20%">
<thead>
<tr>
<th colspan=3 >
Select a Trivia Date
</th>
</tr>
</thead>
<div>
<tr id='currentDateRow'>
<td>
<input type='radio' name='date' value='current' id='current'> Current Date
</td>
</tr>
<tr id='specifiedDateRow'>
<td>
<input type='radio' name='date' value='specified' id='specified'> Specified Date
</td>
</tr>
</div>
<tbody>
</tbody>
</table>
</form>
</body>
</html>
... because when you do currentDateRow.innerHTML = currentDateRow.innerHTML + ... you are recreating the DOM subtree there and you're loosing your event handler(s).

Categories