Как перебрать каждые 3шт. элемента массива по отдельности, если внутри массиве 12 элементов?
При выборе сезона и нажатии на "Ок", во втором select должны добавляться те месяцы, которые относятся к выбранному времени года.
Но условие в том, что нужно использовать два массива: один для времён года и второй для всех месяцев.
Есть ли еще варианты?
const month = document.getElementById("month");
const season = document.getElementById("season");
const display = document.getElementById("display")
let pSeason = {};
let pMonth = {};
pMonth = ["Декабрь","Январь", "Февраль", "Март", "Апрель", "Май", "Июнь", "Июль", "Август", "Сентябрь","Октябрь", "Ноябрь"];
pSeason = ["Зима", "Весна", "Лето","Осень"]
for(let i = 0; i < pSeason.length; i++){
season.innerHTML += "<option>" + pSeason[i] + "</option>"
}
function ok() {
month.innerHTML = "";
display.innerHTML = "";
if(season.value == pSeason[0] ){
for(let i = 0; i < 3 ;i++){
month.innerHTML += "<option>" + pMonth[i] + "</option>";
}
}else if(season.value == pSeason[1]){
for(let i = 3; i < 6 ;i++){
month.innerHTML += "<option>" + pMonth[i] + "</option>";
}
}else if(season.value == pSeason[2]){
for(let i = 6; i < 9 ;i++){
month.innerHTML += "<option>" + pMonth[i] + "</option>";
}
}else if(season.value == pSeason[3]){
for(let i = 9; i < pMonth.length ;i++){
month.innerHTML += "<option>" + pMonth[i] + "</option>";
}
}
}
function ok2(){
display.innerHTML = `Выбран месяц ${month.value} (${season.value})`;
}
<select name="" id="season"></select>
<button onclick="ok()">ok</button>
<select name="" id="month"></select>
<button onclick="ok2()">ok</button>
<p id="display"></p>
Ответы (2 шт):
Автор решения: DiD
→ Ссылка
Первое решение основано, в основом, на CSS:
const months = "Декабрь,Январь,Февраль,Март,Апрель,Май,Июнь,Июль,Август,Сентябрь,Октябрь,Ноябрь".split`,`;
const seasons = "Зима,Весна,Лето,Осень".split`,`;
const option = (ses,idx)=>`<option value="${idx}">${ses}</option>`;
season.innerHTML += seasons.map(option).join``;
month.innerHTML += months.map(option).join``;
style.innerHTML += [...months.keys()].map(
idx => `#season[value="${~~(idx/3)}"]+#month>option:nth-child(${idx+2})`
).join`,` + '{display: list-item;}';
season.oninput = () => ([month.value,output.innerHTML]=[-1,''],
season.setAttribute('value', season.value));
month.oninput = () =>
output.innerHTML = ! months[month.value] ? '' :
'Вы выбрали: ' + seasons[season.value] + '/' + months[month.value];
<select id="season"><option value="-1">Сезон</option></select>
<select id="month"><option value="-1">Месяц</option></select>
<output id="output"></output>
<style id="style">
select { display: block; width: 10rem; height: 1.7rem; }
#month > option { display:none; }
#month > option:nth-child(1) { display: list-item; }
</style>
А здесь базовый вариант:
const months = ["Декабрь","Январь","Февраль","Март","Апрель","Май","Июнь","Июль","Август","Сентябрь","Октябрь","Ноябрь"];
const seasons = ["Зима","Весна","Лето","Осень"];
season.innerHTML += seasons.map(
(ses,idx)=>`<option value="${idx}">${ses}</option>`
).join``;
season.oninput = () => {
output.innerHTML = '';
month.innerHTML = '<option>Месяц</option>'+
months.slice(season.value*3,season.value*3+3)
.map(
(mon,idx)=>`<option value="${season.value*3+idx}">${mon}</option>`
).join``;
};
month.oninput = () => {
output.innerHTML = ! months[month.value] ? '' :
'Вы выбрали: ' +
seasons[season.value] + '/' +
months[month.value];
};
select { display: block; width: 10rem; height: 1.7rem; }
<select id="season"><option>Сезон</option></select>
<select id="month"><option>Месяц</option></select>
<output id="output"></output>
А на radio-элементах можно так:
const months = "Декабрь,Январь,Февраль,Март,Апрель,Май,Июнь,Июль,Август,Сентябрь,Октябрь,Ноябрь".split`,`;
const seasons = "Зима,Весна,Лето,Осень".split`,`;
document.body.innerHTML = seasons.map(
(ses,idx)=>`<input type="radio" name="season" id="season_${idx}" value="${idx}">`
).join`\n` + months.map(
(mon,idx)=>`<input type="radio" name="month" id="month_${idx}" value="${idx}">`
).join`\n`+'\n' + document.body.innerHTML;
fs_seasons.innerHTML += seasons.map(
(ses,idx)=>`<label for="season_${idx}">${ses}</label>`
).join`\n`;
fs_months.innerHTML += months.map(
(mon,idx)=>`<label for="month_${idx}">${mon}</label>`
).join`\n`;
output.innerHTML += seasons.map(
(ses,idx)=>`<label id="season_label_${idx}">${ses}</label>`
).join`\n` +'\n'+
`<span class="separator">/</span>`+'\n' +
months.map(
(mon,idx)=>`<label id="month_label_${idx}">${mon}</label>`
).join`\n`;
style.innerHTML += [...seasons.keys()].map(
idx =>`#season_${idx}:checked~fieldset label[for="season_${idx}"]::before{content:"\\2705";}`
).join`\n`+'\n' + [...seasons.keys()].map(
idx =>`#season_${idx}:checked~#output #season_label_${idx}{display:inline-block;}`
).join`\n`+'\n' + [...months.keys()].map(
idx =>`#month_${idx}:checked~fieldset label[for="month_${idx}"]::before{content:"\\2705";}`
).join`\n`+'\n' + [...months.keys()].map(
idx =>`#month_${idx}:checked~#output #month_label_${idx}{display:inline-block;}`
).join`\n` +'\n' + [...months.keys()].map(
idx =>`#season_${~~(idx/3)}:checked~fieldset label[for="month_${idx}"]{display:inline-block;}`
).join`\n`;
button.onclick = () => {
let inner = document.body.innerHTML;
inner = inner.substr(0,inner.indexOf('<script'));
document.body.innerHTML += `<textarea onblur="this.remove()">${inner}</textarea>`;
document.querySelector('textarea').focus();
button.remove();
}
<style id="style">
input[type="radio"] { display:none }
label { margin: 0 1rem 0 1rem; }
#fs_seasons label::before, #fs_months label::before { content: "\1F532"; }
#fs_months label { display: none; }
#output label { display: none; }
.separator { display: inline-block; margin: 0 1rem 0 1rem; }
textarea { position: fixed; left: 10vw; top: 10vh; width: 80vw; height: 80vh; }
</style>
<fieldset id="fs_seasons"><legend>Сезон</legend></fieldset>
<fieldset id="fs_months"><legend>Месяц</legend></fieldset>
<fieldset id="output"><legend>Вы выбрали</legend></fieldset>
<button id="button">Покажи код</button>
Кстати, последнее решение работает полностью без JS. Тот JS, который там написан только для генерации HTML-кода. Сгенерированный HTML можно посмотреть нажав на кнопку.
Автор решения: UModeL
→ Ссылка
const season = document.getElementById("season");
const month = document.getElementById("month");
const display = document.getElementById("display");
let pSeason = ["Зима", "Весна", "Лето", "Осень"];
let pMonth = ["Декабрь", "Январь", "Февраль", "Март", "Апрель", "Май", "Июнь", "Июль", "Август", "Сентябрь", "Октябрь", "Ноябрь"];
pSeason.forEach(el => {
season.insertAdjacentHTML('beforeend', `<option>${el}</option>`);
})
function ok() {
month.innerHTML = "";
display.innerHTML = "";
pMonth.slice(season.selectedIndex * 3, season.selectedIndex * 3 + 3).forEach(el => {
month.insertAdjacentHTML('beforeend', `<option>${el}</option>`);
})
}
function ok2() {
display.innerHTML = `Выбран месяц ${month.value} (${season.value})`;
}
<select name="" id="season"></select>
<button onclick="ok()">ok</button>
<select name="" id="month"></select>
<button onclick="ok2()">ok</button>
<p id="display"></p>