0 votes
in SoSci Survey (dt.) by s109993 (12.0k points)
edited by s109993

Ich habe ein JS array das ich in eine interne Variablen abspeichern möchte. Jedes Element soll im Besten Fall in eine interne Variable gehen. Es kann theoretisch unbegrenzt viele Elemente geben. Aber in Der Praxis wahrscheinlich nicht mehr als zwanzig.

Edit: ich habe hier einmal den benutzten Code reinkopiert. Der Direktlink zu der Seite ist hier: https://ofb.iea-hamburg.de/test111/?act=s05WcjBtt61ETdqPLDTBsGLd

<div class="date-picker-container">
    <div class="header">
        <button type="button" id="prev-year" class="double-arrow">&lt;&lt;</button>
        <button type="button" id="prev-month" class="arrow">&lt;</button>
        <span id="month-year"></span>
        <button type="button" id="next-month" class="arrow">&gt;</button>
        <button type="button" id="next-year" class="double-arrow">&gt;&gt;</button>
    </div>
    <div class="calendar" id="calendar"></div>
    <br>
    <button type="button" id="show-dates">Select Dates</button>
    <div class="selected-dates" id="selected-dates"></div>
</div>
<script>
document.addEventListener('DOMContentLoaded', function () {
    const calendarElement = document.getElementById('calendar');
    const selectedDatesElement = document.getElementById('selected-dates');
    const showDatesButton = document.getElementById('show-dates');
    const monthYearDisplay = document.getElementById('month-year');
    const prevMonthButton = document.getElementById('prev-month');
    const nextMonthButton = document.getElementById('next-month');
    const prevYearButton = document.getElementById('prev-year');
    const nextYearButton = document.getElementById('next-year');

    let selectedStartDate = null;
    let selectedEndDate = null;
    let currentDate = new Date();
    let allSelectedDates = [];

    const weekdays = ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'];
    const variables = ["XX01_01", "XX01_02","XX01_03", "XX01_04", "XX01_05", "XX01_06", "XX01_07", "XX01_08", "XX01_10", "XX01_11", "XX01_12"];


    function createCalendar(year, month) {
        calendarElement.innerHTML = '';

        // Create row for weekdays
        weekdays.forEach(day => {
            const dayElement = document.createElement('div');
            dayElement.textContent = day;
            dayElement.classList.add('weekday');
            calendarElement.appendChild(dayElement);
        });

        const firstDayOfMonth = new Date(year, month, 1).getDay();
        const daysInMonth = new Date(year, month + 1, 0).getDate();
        
        // Adjust first day to start from Monday
        const startDay = firstDayOfMonth === 0 ? 6 : firstDayOfMonth - 1;

        // Create placeholders for days before the first day of the month
        for (let i = 0; i < startDay; i++) {
            const placeholder = document.createElement('div');
            calendarElement.appendChild(placeholder);
        }

        // Create calendar days
        for (let day = 1; day <= daysInMonth; day++) {
            const dayElement = document.createElement('div');
            dayElement.textContent = day;
            const date = new Date(year, month, day);
            if (date.getDay() === 6 || date.getDay() === 0) {
                dayElement.classList.add('weekend');
            } else {
                dayElement.addEventListener('click', () => toggleDateSelection(date));
            }
            calendarElement.appendChild(dayElement);
        }

        updateCalendar();
    }

    function toggleDateSelection(date) {
        if (date.getDay() === 6 || date.getDay() === 0) {
            return; // Prevent selection of weekends
        }

        if (!selectedStartDate || (selectedStartDate && selectedEndDate)) {
            selectedStartDate = date;
            selectedEndDate = null;
        } else if (date < selectedStartDate) {
            selectedEndDate = selectedStartDate;
            selectedStartDate = date;
        } else {
            selectedEndDate = date;
        }
        updateCalendar();
    }

    function updateCalendar() {
        const dayElements = calendarElement.querySelectorAll('div:not(.weekday)');
        const currentYear = currentDate.getFullYear();
        const currentMonth = currentDate.getMonth();

        dayElements.forEach(dayElement => {
            const day = dayElement.textContent;
            const date = new Date(currentYear, currentMonth, day);
            dayElement.classList.remove('selected', 'in-range');

            // Mark already selected dates with light grey color
            allSelectedDates.forEach(range => {
                if (!range.end && date.toDateString() === range.start.toDateString()) {
                    dayElement.classList.add('selected');
                } else if (range.start && range.end && date >= range.start && date <= range.end) {
                    dayElement.classList.add('in-range');
                }
            });

            // Mark current selected range
            if (selectedStartDate && date.toDateString() === selectedStartDate.toDateString()) {
                dayElement.classList.add('selected');
            }
            if (selectedEndDate && date.toDateString() === selectedEndDate.toDateString()) {
                dayElement.classList.add('selected');
            }
            if (selectedStartDate && selectedEndDate && date > selectedStartDate && date < selectedEndDate) {
                dayElement.classList.add('in-range');
            }
        });

        monthYearDisplay.textContent = `${currentDate.toLocaleString('default', { month: 'long' })} ${currentYear}`;
    }

    function showSelectedDates() {
        if (selectedStartDate) {
            const range = { start: selectedStartDate, end: selectedEndDate };
            allSelectedDates.push(range);
            displaySelectedDates();
            selectedStartDate = null;
            selectedEndDate = null;
            updateCalendar();
        }
    }

    function displaySelectedDates() {
        selectedDatesElement.innerHTML = '';
        allSelectedDates.forEach((range, index) => {
            const rangeElement = document.createElement('div');
            if (range.end) {
                const startDateFormatted = formatDate(range.start);
                const endDateFormatted = formatDate(range.end);
                rangeElement.innerHTML = `<span>${startDateFormatted}</span> -&nbsp; <span> ${endDateFormatted}</span>`;
            } else {
                const startDateFormatted = formatDate(range.start);
                rangeElement.innerHTML = `<span>${startDateFormatted}</span>`;
            }

            const deleteButton = document.createElement('button');
            deleteButton.innerHTML = '&#128465;'; // Unicode for wastebasket
            deleteButton.classList.add('delete-button');
            deleteButton.addEventListener('click', () => deleteSelectedDate(index));

            rangeElement.appendChild(deleteButton);
            selectedDatesElement.appendChild(rangeElement);
        });

    }

    function deleteSelectedDate(index) {
        allSelectedDates.splice(index, 1);
        displaySelectedDates();
        updateCalendar();

    }

    function formatDate(date) {
        const day = date.getDate().toString().padStart(2, '0');
        const month = (date.getMonth() + 1).toString().padStart(2, '0');
        const year = date.getFullYear();
        return `${day}.${month}.${year}`;

date.forEach((element) => {
        console.log(element)
    }
);
console.log(date)

    }

    function changeMonth(offset) {
        currentDate.setMonth(currentDate.getMonth() + offset);
        createCalendar(currentDate.getFullYear(), currentDate.getMonth());
    }

    function changeYear(offset) {
        currentDate.setFullYear(currentDate.getFullYear() + offset);
        createCalendar(currentDate.getFullYear(), currentDate.getMonth());
    }

    showDatesButton.addEventListener('click', showSelectedDates);
    prevMonthButton.addEventListener('click', () => changeMonth(-1));
    nextMonthButton.addEventListener('click', () => changeMonth(1));
    prevYearButton.addEventListener('click', () => changeYear(-1));
    nextYearButton.addEventListener('click', () => changeYear(1));

    createCalendar(currentDate.getFullYear(), currentDate.getMonth());


for (var i=0; i<allSelectedDates.length; i++) {
  var offset = i * 2;
  document.getElementById(variables[offset]).value = allSelectedDates[i]["start"];
  document.getElementById(variables[offset + 1]).value = allSelectedDates[i]["end"];
}





});
</script>

1 Answer

0 votes
by SoSci Survey (327k points)

Eine Möglichkeit wäre, dass Sie im JavaScript ein Array mit Speicherorten (Variablen-IDs) hinterlegen, und die Daten dort hineinschreiben.

var variables = ["IV01_01", "IV01_02", ..., "IV01_20"];

for (var i=0; i<myData.lenth; i++) {
  document.getElementById(variables[i]).value = myData[i];
}

Den Fall, dass das Array mehr als 20 Element hat, müssten sie noch geeignet behandeln/abfangen.

by s109993 (12.0k points)
edited by s109993
Die Daten, welche ich in internen Variablen speichern möchte, werden momentan folgendermaßen abgespeichert:

let allSelectedDates = [
    { start: new Date(2024, 5, 1), end: new Date(2024, 5, 5) },
    { start: new Date(2024, 5, 10) } // A single date with no end date
];

Würde das etwas ändern an der Art und Weise, wie das Script aussieht?

Momentan habe ich es so eingebaut:

var variables = ["XX01_01", "XX01_02","XX01_03", "XX01_04", "XX01_05", "XX01_06", "XX01_07", "XX01_08", "XX01_10", "XX01_11", "XX01_12"];

for (var i=0; i<allSelectedDates.lenth; i++) {
  document.getElementById(variables[i]).value = allSelectedDates[i];
}
by SoSci Survey (327k points)
Naja, Sie müssen halt am Ende wissen, was wo liegt. Wenn Sie immer Wertepaare mit je einem oder zwei Werten haben, dann würde ich empfehlen, dass Sie die Start-Daten immer auf die ungeraten Variablen legen (1, 3, 5, ..) und die End-Daten auf die geraden Variablen (2, 4, 6, ...)

Ihr JavaScript-Code müsste das entsprechend abbilden:

for (var i=0; i<myData.lenth; i++) {
  var offset = i * 2;
  document.getElementById(variables[offset]).value = allSelectedDates[i]["start"];
  document.getElementById(variables[offset + 1]).value = allSelectedDates[i]["end"];
}
by s109993 (12.0k points)
Ich glaube, es hat funktioniert. Jedenfalls sind erstmal Daten in SoSci angekommen, was schon einmal ein großer Schritt ist. Danke!

Willkommen im Online-Support von SoSci Survey.

Hier bekommen Sie schnelle und fundierte Antworten von anderen Projektleitern und direkt von SoSci Survey.

→ Eine Frage stellen


Welcome to the SoSci Survey online support.

Simply ask a question to quickly get answers from other professionals, and directly from SoSci Survey.

→ Ask a Question

...