<select>
<option value="2022-05-01">May 2022</option>
<option value="2022-04-01">April 2022</option>
<option value="2022-03-01">March 2022</option>
<option value="2022-02-01">February 2022</option>
<option value="2022-01-01">January 2022</option>
<option value="2021-12-01">December 2021</option>
<option value="2021-11-01">November 2021</option>
<option value="2021-10-01">October 2021</option>
<option value="2021-09-01">September 2021</option>
<option value="2021-08-01">August 2021</option>
<option value="2021-07-01">July 2021</option>
<option value="2021-06-01">June 2021</option>
<option value="2021-05-01">May 2021</option>
</select>
As we can see here the month starts from May and goes till last year May. I want this list to be dynamic and the value of the option to be as shown. I am new to html and JS any help is appreciated.
CodePudding user response:
Here you are :)
let d = new Date(), currentYear = d.getFullYear(), currentMonth = d.getMonth(), month, months, sortedMonths, sortedIndexes = [];
// 'long' or 'short'
month = 'long' //example: 'January' or 'Jan'
months = Array.from({length: 12}, (e, i) => {return new Date(null, i 1, null).toLocaleDateString("en", {month: month})});
sortedMonths = [...months.slice(0,currentMonth 1).reverse(), ...months.slice(currentMonth 1).reverse(), months[currentMonth]]; sortedMonths.forEach(m => {sortedIndexes.push(months.indexOf(m) 1)});
// returns NAME for <option> -> May 2022
const sortedNames = [...months.slice(0, currentMonth 1).reverse().map(m =>`${m} ${currentYear}`), ...months.slice(currentMonth 1).reverse().map(m =>`${m} ${currentYear-1}`), `${months[currentMonth]} ${currentYear - 1}`];
// returns Value for <option> -> 2022-05-01
const sortedValues = [...months.slice(0, currentMonth 1).reverse().map(m => currentYear),...months.slice(currentMonth 1).reverse().map(m => currentYear - 1), currentYear - 1];
sortedValues.forEach((e, i) => {(sortedIndexes[i].toString().length < 2 ? sortedIndexes[i] = '0' sortedIndexes[i].toString() : sortedIndexes[i] = sortedIndexes[i].toString()), sortedValues[i] = `${e}-${sortedIndexes[i]}-01`});
// creates Select node and options
const dropDown = document.createElement('select');
sortedNames.forEach((e, i) => {
const option = document.createElement('option');
option.value = sortedValues[i];
option.textContent = sortedNames[i]
dropDown.append(option);
});
//you can delete this part just added it to show the result
document.body.append(dropDown)