I have a requirement to add a standard drop-down from which you can select a date value (month/year) and based on a date you select, three check-boxes will show right below the drop-down of the next 3 calendar quarters.
For ex. if you were to select September 2011 from the drop-down, it would show check-boxes for Q4 2011, Q1 2012, Q2 2012. Since September 2011 is Q3 2011.
Is there a way to do this without hard-coding the year value? I appreciate the help!
select markup would be:
<select name="selectMonth">
<option value="month1">Janurary 2011/option>
<option value="month2">June 2011</option>
<option value="month3">December 2011</option>
<option value="month3">February 2012</option>
</select>
This is my friend’s JS interpretation, though it uses a timestamp:
var Selected = "2012-03-28";
var Date = new Date(Selected);
var After = Date.getMonth()+3;
var Before = Date.getMonth()-3;
function sayQuarter(date) {
var m = Date.getMonth(date);
var y = Date.getYear(date);
var q = floor((m / 3) + 0.9);
if (q.length == 1) { q = "0"+q; }
return "Q"+q+" "+y;
}
var output = "3mo Before = "+Before+" ... "+sayQuarter.Before+"<br/>"+
"Selected = "+Selected+" ... "+sayQuarter.Selected+"<br/>"+
"3mo After = "+After+" ... "+sayQuarter.After+"<br/>";
if (document.getElementById('hello')) {
document.getElementById('hello').innerHTML = output;
}
I need to essentially do this with Javascript and have it check based on values within a select dropdown. Thoughts?
First of all, we have to prepare some elements. Since you don’t want to save every year, it’s better to create the
selectelement dynamically:We fill them when the page is loaded and add them to the document:
Please note that you have to use
attachEventor.onload/.onchangein Internet Explorer prior to version 9(?) instead ofaddEventListener. You could create and fill the elements also at the beginning of your script, but you can’t append them before the DOM is loaded.Now when the user changes the value in either
monthSelectionoryearSelectionupdateQuartalsgets called:If the
quartalWrapperhas no parent node we create the labels and checkboxes, since that means it’s not yet appended to the document:Then we will update all three children labels and checkboxes. Note that
label.firstChildis the checkbox, whilelabel.lastChildis thetextNodewe created above.quartalWrapper.childNodes[i]is actually one of thelabels.Since the following quartals are always defined for a given month we can hardcode them into the function
getQuartals:Notice that the first value is the quarter and the second one is the year offset. You could also calculate these arrays:
Jsfiddle demonstrations: using hardcoded values, using calculation.
Note that this solution doesn’t use jQuery. If you want to use jQuery feel free to change the code (use
$()or.oninstead ofaddEventListener(),.append,…).