How to make a cascading selection?

  • 0
    There are 2 select with values, in the first event, in the 2 date of this event.
    Help make a cascading selection, that is: 1 event has its own dates, 2 have their own, and when you select each in the second select, there were specific dates.
    JavaScript Hanna Mora, Apr 7, 2020

  • 3 Answers
  • 0
    <select id="event"></select>
    <select id="dates"></select>


    const events = [
    { name: '...', dates: [ ... ] },
    { name: '...', dates: [ ... ] },
    ...
    ];

    const eventEl = document.querySelector('#event');
    const datesEl = document.querySelector('#dates');

    eventEl.innerHTML = events
    .map((n, i) => `<option value="${i}">${n.name}</option>`)
    .join('');

    eventEl.addEventListener('change', function() {
    datesEl.innerHTML = events[this.value].dates
    .map(n => `<option>${n}</option>`)
    .join('');
    });

    eventEl.dispatchEvent(new Event('change'));
    Anonymous

  • 0

  • 0
    <div class="events-block">
    <select id="events">
    <option value="">Выберите ивент</option>
    <option value="even1" data-dates="1 января 2038г., 18 июля 2073г., 28 мая 2133г.">Мероприятие 1</option>
    <option value="even2" data-dates="31 марта 2031г., 8 июня 2083г., 1 мая 2303г.,30 февраля 2581г.">Мероприятие 2</option>
    </select>
    </div>


    document.getElementById('events').addEventListener('change', function(e){
    let option = e.target.options[e.target.selectedIndex];
    let eventDates = document.getElementById('eventDates');
    if('dataset' in option && 'dates' in option.dataset){
    let dateArr = option.dataset.dates.split(',');
    if(eventDates === null){
    eventDates = document.createElement('select');
    eventDates.id = 'eventDates';
    this.after(eventDates);
    }
    while(eventDates.firstChild) {
    eventDates.firstChild.remove();
    }
    let optionDate = document.createElement('option');
    optionDate.textContent = optionDate.value = 'Выберите дату';
    eventDates.appendChild(optionDate);
    dateArr.forEach(v=>{
    let option = document.createElement('option');
    option.textContent = option.value = v.trim();
    eventDates.appendChild(option);
    });
    } else {
    eventDates.remove();
    }
    });
    Anonymous

Your Answer
To place the code, please use CodePen or similar tool. Thanks you!