다른 게시판에서 값을 가져와서 계산할때 자바스크립트 안에 값을 어떻게 배열해야하나요?

A게시판에서 입력한 차량 종류별 거리에 따라 금액을 계산하는 소스를 구성했습니다.

계산까지는 자바스크립트로 구현했는데, 거리 선택했을때 해당 차량의 값을 불러오는 부분을 어떤 코드로 넣어야할지 막막하여 문의 드립니다.

 

### 구현 소스 ###

   <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <link rel="stylesheet" href="https://code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
    <script src="https://code.jquery.com/ui/1.12.1/jquery-ui.min.js"></script>

    <div>
        <!-- Total display -->
        Total: <span id="total"></span>
    </div>

    <!-- Booking selection elements -->
    <select id="m4r1InfoMrO" name="m4r1InfoMrO">
        <option value="1">One way</option>
        <option value="2">Round trip</option>
    </select><br><br>

    <!-- Seat selections -->
    <select id="m4r1InfoMrP" name="m4r1InfoMrP">
        <option value="0">0</option>
        <option value="1">1</option>
        <option value="2">2</option>
        <option value="3">3</option>
        <option value="4">4</option>
    </select><br><br>

    <select id="m4r1InfoMrS" name="m4r1InfoMrS">
        <option value="0">0</option>
        <option value="1">1</option>
        <option value="2">2</option>
        <option value="3">3</option>
        <option value="4">4</option>
    </select><br><br>

    <select id="m4r1InfoMrJ" name="m4r1InfoMrJ">
        <option value="0">0</option>
        <option value="1">1</option>
        <option value="2">2</option>
        <option value="3">3</option>
        <option value="4">4</option>
    </select><br><br>

    <select id="m4r1InfoMrK" name="m4r1InfoMrK">
        <option value="0">0</option>
        <option value="1">1</option>
        <option value="2">2</option>
        <option value="3">3</option>
        <option value="4">4</option>
    </select><br><br>

    <!-- Distance selection -->
    <select id="m4r1InfoMrD" name="m4r1InfoMrD">
        <option value="100">100</option>
        <option value="125">125</option>
        <option value="150">150</option>
        <option value="175">175</option>
    </select>

    <!-- Date pickers for departure and arrival -->
    <div>
        <input type="text" id="departure" class="datepicker" placeholder="Departure Date" readonly>
        <label class="floating_label">Departure</label>
    </div>
    <div>
        <input type="text" id="arrival" class="datepicker" placeholder="Arrival Date" readonly>
        <label class="floating_label">Arrival</label>
    </div>

    <!-- Hidden input for the final price -->
    <input id="m4r1InfoMrPS" readonly>

    <script>
        $(document).ready(function () {
            // Initialize date pickers
            $('.datepicker').datepicker({
                dateFormat: 'yy-mm-dd',
                showMonthAfterYear: true,
                yearSuffix: 'year',
                monthNames: ['1', '2', '3', '4', '5', '6', '7', '8', '9', '10', '11', '12'],
                dayNames: ['sun', 'mon', 'tue', 'wed', 'thu', 'fri', 'sat'],
            });

            // Event listeners for calculating price
            $('#m4r1InfoMrP, #m4r1InfoMrS, #m4r1InfoMrJ, #m4r1InfoMrK, #m4r1InfoMrD, #m4r1InfoMrO, #departure, #arrival')
                .change(calculate);

            calculate(); // Initial calculation
        });

        // Function to get the season based on the date
        function getSeason(dateStr) {
            const date = new Date(dateStr);
            const month = date.getMonth() + 1; // JS months are 0-based
            return month >= 5 && month <= 9 ? 'peak' : 'low';
        }

        // Price data for peak and low seasons
        const prices = {
            peak: {
                '9': { '100': 180000, '125': 200000, '150': 220000, '175': 240000 },
                '15': { '100': 300000, '125': 320000, '150': 350000, '175': 380000 },
                '25': { '100': 450000, '125': 500000, '150': 550000, '175': 600000 }
            },
            low: {
                '9': { '100': 140000, '125': 150000, '150': 160000, '175': 170000 },
                '15': { '100': 190000, '125': 200000, '150': 210000, '175': 220000 },
                '25': { '100': 370000, '125': 380000, '150': 390000, '175': 400000 }
            }
        };

        // Function to get price based on season, seat type, and distance
        function getPrice(season, seatType, distance) {
            return (prices[season] && prices[season][seatType] && prices[season][seatType][distance]) || 0;
        }

        // Calculate function
        function calculate() {
            const seatCounts = {
                '9': +$('#m4r1InfoMrP').val(),
                '15': +$('#m4r1InfoMrS').val(),
                '25': +$('#m4r1InfoMrJ').val(),
                '45': +$('#m4r1InfoMrK').val()
            };
            const distance = $('#m4r1InfoMrD').val();
            const tripType = $('#m4r1InfoMrO').val();
            const departureDate = $('#departure').val();
            const arrivalDate = $('#arrival').val();

            let total_price = 0;

            // Debugging outputs
            console.log("Seat Counts:", seatCounts);
            console.log("Distance:", distance);
            console.log("Trip Type:", tripType);
            console.log("Departure Date:", departureDate);
            console.log("Arrival Date:", arrivalDate);

            if (tripType === '1') { // One-way trip
                const season = getSeason(departureDate);
                console.log("Season (One-way):", season);
                for (const [seatType, count] of Object.entries(seatCounts)) {
                    if (count > 0) total_price += count * getPrice(season, seatType, distance);
                }
            } else if (tripType === '2') { // Round trip
                const seasonDeparture = getSeason(departureDate);
                const seasonArrival = getSeason(arrivalDate);

                console.log("Season (Departure):", seasonDeparture);
                console.log("Season (Arrival):", seasonArrival);

                for (const [seatType, count] of Object.entries(seatCounts)) {
                    if (count > 0) {
                        total_price += count * getPrice(seasonDeparture, seatType, distance);
                        total_price += count * getPrice(seasonArrival, seatType, distance);
                    }
                }
            }

            console.log("Total Price:", total_price);

            $('#m4r1InfoMrPS').val(total_price);
            $('#total').text(total_price);
        }
    </script>

 

A게시판에 대한 정보는 불러왔는데 아래 값을 매핑하는 부분을 javascript 에 어떻게 배열해야할까요?

여기서 9인승 15인승 25인승에 대한 값은

$document->category1 == '9인승'

 

비수기 성수기 구분 값은 

$document->category2 == '비수기'

 

'거리 : 금액' 구분 값은

$document->title : $document->option->distance_price

 

예를 들어 9인승에 대한 거리별 금액 (성수기, 비수기 구분 포함)

<select>
<?php foreach($results as $item):?>
	<?php
	$document = new KBContent();
	$document->initWithUID($item->uid);
	?>
		<?php if($document->category1 == '9인승' && $document->category2 == '성수기'):?>
			<option value="<?php echo $document->title?>-<?php echo $document->option->distance_price?>"><?php echo $document->title?>--<?php echo $document->option->distance_price?></option>
		<?php endif?>
<?php endforeach?>
</select>
<select>
<?php foreach($results as $item):?>
	<?php
	$document = new KBContent();
	$document->initWithUID($item->uid);
	?>
		<?php if($document->category1 == '9인승' && $document->category2 == '비수기'):?>
			<option value="<?php echo $document->title?>-<?php echo $document->option->distance_price?>"><?php echo $document->title?>--<?php echo $document->option->distance_price?></option>
		<?php endif?>
<?php endforeach?>
</select>

이렇게 불러올 수 있습니다.

 

 

이 부분만 해결하면 될것 같은데요, 가능하다면 알려주세요.

const prices = {
	peak: {
		'9': { '100': 180000, '125': 200000, '150': 220000, '175': 240000 },
		'15': { '100': 300000, '125': 320000, '150': 350000, '175': 380000 },
		'25': { '100': 450000, '125': 500000, '150': 550000, '175': 600000 }
	},
	low: {
		'9': { '100': 140000, '125': 150000, '150': 160000, '175': 170000 },
		'15': { '100': 190000, '125': 200000, '150': 210000, '175': 220000 },
		'25': { '100': 370000, '125': 380000, '150': 390000, '175': 400000 }
	}
};

 

좋은 정보와 인맥을 동시에, 워드프레스 사용자 단톡방 참여하기
좋은 정보와 인맥을 동시에, 워드프레스 사용자 단톡방 참여하기
좋은 정보와 인맥을 동시에, 워드프레스 사용자 단톡방 참여하기