JavaScript Data Calculator - Calendar Selection & Submit Functions



It's the final week of our coding project and the Date Calculator I have been working on the past couple weeks is complete. This week I added functionality to the radio buttons and the calculate button.

The radio buttons not only select the calculator the user wants, but they control which elements are visible on the page. The second calendar picker is only needed when comparing the number of days between two dates, so it is hidden when not in use. The same goes for the Number of Days input box which corresponds to adding/subtracting a number of days from a selected date.

Previously, I hard coded a specific date calculator's function to the CALCULATE button for testing, but now it needs to call the correct function based on the selected radio button. Let's dive in on wiring up the radio buttons.

Control Visibility Using Radio Buttons

In order to access the radio buttons using JavaScript, I needed to make sure the form had a distinctive id, that each button in the list was coded with a value, like an index, and that they all had the same name, so I could loop through the form's elements.

Then, I created three functions;  displayOptions(), and calcOptions(). You can see the full code with each function below, but let's talk about what they do.

  • displayOptions (cal2Visible, inputBoxVisible), takes in two booleans to designate the visibility of the mycalendar2 calendar picker and the daysInput text box using conditional statements.
  • calcOptions(selectedIndex) takes in a value representing the index of the selected radio button and uses a conditional to call displayOptions with boolean values for whether the two controls should be visible to the user.

As you can see in the image above, calcOptions() is called in the onclick event handler for each radio button, with the index value hard-coded. Each time a radio button is selected, the method is called, toggling the controls that are visible. The image below shows how the display changes, based on radio button selection.


Wiring the Calculate Button

Getting the calculate button to work required the creation of  three new functions. One to get the value of the selected radio button, one to call the correct calculation function, based on that value, and one to call both functions when the button is clicked.

  • getRadioVal(form,name) loops through the elements of the form parameter (calcRadioButtons), checking each element matching the name parameter (calculator) to see if it is clicked. It returns the value from the element that is clicked. 
  • calcResult(selectedCalendar) uses a conditional switch statement to call the calculation function that matches the case value (selectedCalendar) which represents the index/value of the selected radio button.
  • calculate() calls getRadioVal() and stores its value in a local variable which is used in the calcResult() method.


Date Calculator JavaScript Code

Toggling Display Options

//toggles the visiblity of controls function displayOptions(cal2Visible,inputBoxVisible) { //resets the text values of labels and input box document.getElementById("warningText").innerHTML = ""; document.getElementById("resultText").innerHTML = ""; document.getElementById("incrementDayNum").value = ""; if(cal2Visible) { document.getElementById("mycalendar2").style.visibility = "visible"; document.getElementById("selectText2").style.visibility = "visible"; } else { document.getElementById("mycalendar2").style.visibility = "hidden"; document.getElementById("selectText2").style.visibility = "hidden"; document.getElementById("selecteddate2").style.visibility = "hidden"; } if(inputBoxVisible) { document.getElementById("daysInput").style.visibility = "visible"; } else { document.getElementById("daysInput").style.visibility = "hidden"; } } //changes the visibility of controls based on selected radio button function calcOptions(selectedIndex) { switch(selectedIndex) { case 0: { displayOptions(false,false); break; } case 1: { displayOptions(true,false); break; } case 2: case 3: { displayOptions(false,true); break; } } }

Calculate Button Functions

For some reason, when I paste this code in the embedded editor, Blogger freaks out, and I'm not arguing with it anymore. So, here is the code to get the value of the radio button.
//calls the corresponding date calc method based on selected radio button function calcResult(selectedCalculator) { document.getElementById("warningText").innerHTML = ""; let calc = parseInt(selectedCalculator); switch(calc){ case 0: { daysUntil(); break; } case 1: { daysBetween(); break; } case 2: { incrementDays(2); break; } case 3: { incrementDays(3); break; } } } //gets the radio button index and uses it to call calcResult() function calculate(){ var calcIndex = getRadioVal( document.getElementById('calcRadioButtons'), 'calculator' ); calcResult(calcIndex); }

Calculation Fucntions

//operation type is determined by radio button (2 = add, 3 = subtract) function incrementDays(operationType) { //check for user input in calendar and text box let inputDate = document.getElementById("selecteddate1").innerText; let calcDate = new Date("\"" + inputDate + "\""); let incDayNum = document.getElementById("incrementDayNum").value; if(inputDate !== "" && incDayNum !== "" && !isNaN(incDayNum)) { let incrementAmt; let startDate = new Date(calcDate); let operationText; let toFromText; let resultDate = new Date(calcDate); let resultText; //if adding (type 2), increment is parsed as a positive. //else subtracting (type 3), increment is parsed as a negative. if(operationType === 2) { //convert the input days text to Float incrementAmt = parseFloat(incDayNum); operationText = "Adding"; //grammar change for 1 vs multiple days if(incrementAmt !== 1 ) { toFromText = " days to "; } else { toFromText = " day to "; } } else { incrementAmt = -1 * parseFloat(incDayNum); operationText = "Subtracting"; //grammar change for 1 vs multiple days if(incrementAmt !== 1) { toFromText = " days from "; } else { toFromText = " day from "; } } resultDate.setDate(startDate.getDate() + incrementAmt); resultText = operationText + " " + incDayNum + toFromText + startDate.toDateString() + " equals " + resultDate.toDateString(); document.getElementById("resultText").innerHTML = resultText; } else { document.getElementById("warningText").innerHTML = "Please select a date and " + "enter the number of days to add or substract"; } } //calculates the num of days until a future date function daysUntil () { let today = new Date(); let inputDate = document.getElementById("selecteddate1").innerText; let futureDate = new Date("\"" + inputDate + "\""); let numDaysUntil; if (futureDate > today) { numDaysUntil = Math.ceil((futureDate.getTime() - today.getTime())/(1000 * 60 * 60 * 24)); let resultText; if (numDaysUntil === 1) { resultText = "There is " + numDaysUntil + " day from today, " + today.toDateString() + ", until " + futureDate.toDateString(); } else { resultText = "There are " + numDaysUntil + " days from today, " + today.toDateString() + ", until " + futureDate.toDateString(); } document.getElementById("resultText").innerHTML = resultText; } else { document.getElementById("warningText").innerHTML = "Please select a date in the future"; } } //calculates the num of days between two dates function daysBetween () { let inputDate1 = document.getElementById("selecteddate1").innerText; let inputDate2 = document.getElementById("selecteddate2").innerText; let date1 = new Date("\"" + inputDate1 + "\""); let date2 = new Date("\"" + inputDate2 + "\""); let dateDifference; let resultText; //checking to make sure user selected two dates if(inputDate1 !== "" && inputDate2 !== "") { //use absolute value to make sure difference is always positive dateDifference = Math.abs(date1.getTime() - date2.getTime()); //convert from milliseconds to days dateDifference = Math.floor(dateDifference/(1000 * 60 * 60 * 24)); //grammar check for 1 vs multiple days if(dateDifference ===1) { resultText = "There is " + dateDifference + " day between " + date1.toDateString() + " and " + date2.toDateString(); } else { resultText = "There are " + dateDifference + " days between " + date1.toDateString() + " and " + date2.toDateString(); } document.getElementById("resultText").innerHTML = resultText; } else { document.getElementById("warningText").innerHTML = "Please select a date on both calendars"; } }

I attempted to host this at mmismas21.000webhostapp.com so you could play with the calculator yourself, but for some reason the calendar pickers aren't loading. The YUI libraries aren't supported anymore, so that may be the issue, even though it worked correctly during testing. Go figure. I hope you enjoyed this journey into creating a JavaScript Date Calculator. I look forward to hearing any questions or feedback you may have.

Comments