I wish to build something similar to this:
The general conditions are:
Up to the 10th day of the current month the next three months should be displayed. As an example: today’s date should produce 1st May, 1st June and 1st July.
After the 10th day of the current month, the months after next should appear. Example: 11th April should creates 1st July, 1st August and 1st September.
The annual transition should be taken into account. The generated data should each be selectable as radio buttons, but only one at a time.
I know the following doesn’t work, but I’m a beginner trying to learn and understand JavaScript.
const date = new Date();
let day = date.getDate();
let month = date.getMonth() + 1;
let year = date.getFullYear();
if (day < 10) {
let month_1 = month + 1
let month_2 = month + 2
let month_3 = month + 3
if (month + 3 > 12) {
let month_3 = 12 - month + 3
}
if (month + 2 > 12) {
let month_2 = 12 - month + 2
}
if (month + 1 > 12) {
let month_1 = 12 - month + 1
}
console.log(month_1, month_2, month_3)
} else {
let month_1 = month + 2
let month_2 = month + 3
let month_3 = month + 4
if (month + 4 > 12) {
let month_3 = 12 - month + 4
}
if (month + 3 > 12) {
let month_2 = 12 - month + 3
}
if (month + 2 > 12) {
let month_1 = 12 - month + 2
}
console.log(month_1, month_2, month_3)
}
3
Answers
You can dynamically generate HTML elements (like radiobuttons) with the methods of the
document
object. And the date arithmetic is rather simple using the methods of theDate
class. (But I initially overlooked that you must set the day to 1 before shifting months, otherwise adding one month to2023-03-31
gives2023-05-01
.)It is important to give all radiobuttons the same
name
, but differentvalue
s. Upon submitting the form, the request will then contain a parameter likestartDate=01.05.2023
. (Initially I wanted to usedate.toISOString()
, but that produces the date in UTC, which may differ from the date in the user’s time zone.)It’s good practice to use the var instead of let since you’re reassigning the values of the coming months (month_1) when you loop over back to the beginning of the year. Just to make sure that the new value of your variable can be accessed outside the if statement, generally this is case and could be the reason you’re having an issue.
Some the issues I think you had were:
Using less or greater than 10 days, using let and subtracting 12 from the wrong side or else I think the rest should work.
Here’s a fixed version of the code:
If you want to make it so that only one radio button can be selected at a time. You have to add a name to the inputs and keep it the same for all the radios.
ex:
<input type="radio" name="Date" />
Good luck on your coding journey
you can use the switch statement too(you can google it) I wrote the additional explanation as comments inside my code.