mutu-rsab/resources/views/soal/index.blade.php

926 lines
36 KiB
PHP

@extends('layouts.template')
@section('title', 'Kuesioner Soal')
@section('custom_css')
<link rel="stylesheet" href="{{ asset('vuexy/assets/vendor/libs/select2/select2.css') }}">
<style>
.question-card {
border: 1px solid #dee2e6;
border-radius: 12px;
padding: 1.25rem;
background: #fff;
box-shadow: 0 4px 18px rgba(0, 0, 0, 0.04);
}
.question-layout .question-text-col {
border-right: 1px solid #f1f3f5;
}
.question-layout .answer-section {
padding-left: 1.5rem;
}
@media (max-width: 767.98px) {
.question-layout .question-text-col {
border-right: 0;
border-bottom: 1px dashed #e9ecef;
padding-bottom: 1rem;
margin-bottom: 1rem;
}
.question-layout .answer-section {
padding-left: 0;
}
}
.option-scroll {
max-height: 220px;
overflow-y: auto;
border: 1px dashed #ced4da;
border-radius: 0.65rem;
padding: 0.75rem 1rem;
background-color: #f8f9fa;
}
.select2-container {
width: 100% !important;
}
.select2-container .select2-selection--single {
min-height: calc(2.625rem + 2px);
padding: 0.5rem 1rem;
border: 1px solid #ced4da;
border-radius: 0.5rem;
}
.select2-container--default .select2-selection--single .select2-selection__rendered {
line-height: 1.6;
color: #4f4f4f;
}
.select2-container--default .select2-selection--single .select2-selection__arrow {
top: 0.6rem;
right: 1rem;
}
.option-scroll::-webkit-scrollbar {
width: 6px;
}
.option-scroll::-webkit-scrollbar-thumb {
background-color: rgba(13, 110, 253, 0.4);
border-radius: 3px;
}
.lainnya-input {
display: none;
}
.lainnya-input.show {
display: block;
margin-top: 0.85rem;
}
.dual-form-wrapper .form-label {
font-weight: 600;
}
</style>
@endsection
@section('content')
@php
$listHal = $daftarHal ?? collect([$hal]);
$posisiAktif = $listHal->search($hal);
if ($posisiAktif === false) {
$posisiAktif = 0;
}
$totalHalaman = $totalHal ?? $listHal->count();
$progressPercentage = $totalHalaman > 0 ? round((($posisiAktif + 1) / max($totalHalaman, 1)) * 100) : 100;
$halSebelumnya = $posisiAktif > 0 ? $listHal[$posisiAktif - 1] : null;
$halBerikut = ($posisiAktif < $listHal->count() - 1) ? $listHal[$posisiAktif + 1] : null;
$isHalTerakhir = $halBerikut === null;
@endphp
<div class="py-4">
<div class="row justify-content-center">
<div class="col-xl-8 col-lg-10">
<div class="d-flex flex-column flex-md-row align-items-md-center justify-content-between gap-2 mb-3">
<div>
<p class="text-muted mb-1">Kuesioner</p>
<h3 class="fw-semibold mb-0">{{ $soal->judul_soal ?? 'Daftar Soal' }}</h3>
</div>
<div class="d-flex align-items-center gap-2">
<a href="{{ route('soal.index') }}" class="btn btn-outline-secondary btn-sm">
&larr; Daftar Judul
</a>
<span class="badge bg-label-primary fs-6 px-3 py-2" id="badge-hal">Halaman {{ $hal }}</span>
</div>
</div>
<div class="card border-0 shadow-sm mb-4">
<div class="card-body">
<div class="d-flex justify-content-between small text-muted mb-1">
<span>Progres Halaman</span>
<span id="progress-text">{{ $progressPercentage }}%</span>
</div>
<div class="progress" style="height: 8px;">
<div class="progress-bar" id="progress-bar" role="progressbar" style="width: {{ $progressPercentage }}%;" aria-valuenow="{{ $progressPercentage }}" aria-valuemin="0" aria-valuemax="100"></div>
</div>
</div>
</div>
@if ($hal === $halPertama)
<div class="card border-0 shadow-sm mb-4" id="head_soal">
<div class="card-body">
<h5 class="mb-3 text-primary">{{ $soal->judul_soal ?? '-' }}</h5>
<div class="border rounded p-3 bg-light text-body">
{!! $soal->keterangan_soal !!}
</div>
</div>
</div>
@endif
@if ($errors->any())
<div class="alert alert-danger alert-dismissible fade show" role="alert">
<strong>Terjadi kesalahan.</strong> Silakan periksa kembali jawaban Anda.
<button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
</div>
@endif
<div class="d-flex justify-content-between align-items-center mb-3 flex-wrap gap-2">
<h5 class="mb-0">Daftar Pertanyaan</h5>
<small class="text-muted" id="summary-hal">Halaman {{ $hal }} dari {{ $listHal->count() }}</small>
</div>
<form id="form-soal" method="POST" action="{{ route('soal.store') }}" data-hal-list='@json($listHal->values())'>
@csrf
<input type="hidden" name="lms_mutu_soal_id" value="{{ $soal->id }}">
<input type="hidden" name="hal" id="input-hal" value="{{ $hal }}">
@forelse ($soal->soalDetail as $detail)
@php
$detailConfig = json_decode($detail->soal, true) ?? [];
$pertanyaan = $detailConfig['soal'] ?? 'Pertanyaan tidak tersedia';
$type = $detailConfig['type'] ?? 'option';
$options = $detailConfig['options'] ?? [];
if (!is_array($options)) {
$options = [];
}
$optionValues = collect($options)->map(function ($value) {
return is_scalar($value) ? (string) $value : '';
})->all();
$oldAnswer = old('jawaban.' . $detail->id);
$oldOtherAnswer = old('jawaban_lainnya.' . $detail->id);
$hasOldAnswer = $oldAnswer !== null && $oldAnswer !== '';
$isCustomOldAnswer = $hasOldAnswer && !in_array($oldAnswer, $optionValues, true);
if (!$oldOtherAnswer && $isCustomOldAnswer) {
$oldOtherAnswer = $oldAnswer;
}
$showLainnya = $isCustomOldAnswer
|| (is_string($oldAnswer) && stripos($oldAnswer, 'lainnya') !== false)
|| (!empty($oldOtherAnswer));
$detailHal = $detail->hal ?? $listHal->first();
$isVisible = $detailHal == $hal;
$optionsCount = is_array($options) ? count($options) : 0;
$useSelectSearch = $optionsCount > 4;
$hasLainnyaOption = collect($options)->contains(function ($optionItem) {
return is_string($optionItem) && stripos($optionItem, 'lainnya') !== false;
});
if (!$hasLainnyaOption && $type === 'option_with_other') {
$hasLainnyaOption = true;
}
$isConsentQuestion = !empty($detailConfig['persetujuan_form']);
$shouldForceLainnyaSelection = $hasLainnyaOption && $showLainnya;
$dualFormConfig = $detailConfig['dual_form'] ?? null;
$useDualForm = $type === 'dual_form' || (!empty($dualFormConfig) && $dualFormConfig !== false);
$dualYearOld = null;
$dualMonthOld = null;
if ($useDualForm && $oldAnswer) {
if (preg_match('/([0-9]+)\\s*\\(Tahun\\)/i', $oldAnswer, $matchYear)) {
$dualYearOld = $matchYear[1];
}
if (preg_match('/([0-9]+)\\s*\\(Bulan\\)/i', $oldAnswer, $matchMonth)) {
$dualMonthOld = $matchMonth[1];
}
}
@endphp
<div class="question-card mb-4"
data-hal-card="{{ $detailHal }}"
data-detail-id="{{ $detail->id }}"
data-consent-question="{{ $isConsentQuestion ? '1' : '0' }}"
data-question-type="{{ $type }}"
style="{{ $isVisible ? '' : 'display: none;' }}">
<div class="row g-3 align-items-start question-layout">
<div class="col-md-6 question-text-col">
<div class="d-flex align-items-center gap-3 mb-1">
<span class="badge rounded-pill bg-label-primary fs-6">{{ $loop->iteration }}</span>
<h5 class="fw-semibold mb-0">{{ $pertanyaan }}</h5>
</div>
@if ($isConsentQuestion)
<p class="text-muted small mb-0">Pertanyaan persetujuan</p>
@endif
</div>
<div class="col-md-6 answer-section">
@if ($useDualForm)
<div class="dual-form-wrapper" data-dual-wrapper="{{ $detail->id }}">
<div class="row g-3">
<div class="col-sm-6">
<label class="form-label small text-muted mb-1">Tahun</label>
<input type="number" min="0" class="form-control"
data-dual-input="tahun"
value="{{ $dualYearOld }}"
data-field-hal="{{ $detailHal }}"
placeholder="Masukkan tahun">
</div>
<div class="col-sm-6">
<label class="form-label small text-muted mb-1">Bulan</label>
<input type="number" min="0" class="form-control"
data-dual-input="bulan"
value="{{ $dualMonthOld }}"
data-field-hal="{{ $detailHal }}"
placeholder="Masukkan bulan">
</div>
</div>
<input type="hidden"
class="@error('jawaban.' . $detail->id) is-invalid @enderror"
name="jawaban[{{ $detail->id }}]"
value="{{ old('jawaban.' . $detail->id) }}"
data-dual-hidden="{{ $detail->id }}"
data-field-hal="{{ $detailHal }}"
@if ($isConsentQuestion) data-consent-input="1" @endif
required>
</div>
@elseif ($type === 'textarea')
<textarea class="form-control @error('jawaban.' . $detail->id) is-invalid @enderror"
name="jawaban[{{ $detail->id }}]" rows="4" required
data-field-hal="{{ $detailHal }}"
@if ($isConsentQuestion) data-consent-input="1" @endif
placeholder="Tulis jawaban Anda di sini">{{ old('jawaban.' . $detail->id) }}</textarea>
@elseif ($type === 'text')
<input type="text" class="form-control @error('jawaban.' . $detail->id) is-invalid @enderror"
name="jawaban[{{ $detail->id }}]" value="{{ old('jawaban.' . $detail->id) }}" required
data-field-hal="{{ $detailHal }}"
@if ($isConsentQuestion) data-consent-input="1" @endif
placeholder="Masukkan jawaban Anda">
@else
@if (!empty($options))
@if ($useSelectSearch)
<select class="form-select select2 @error('jawaban.' . $detail->id) is-invalid @enderror"
name="jawaban[{{ $detail->id }}]"
data-field-hal="{{ $detailHal }}"
@if ($isConsentQuestion) data-consent-input="1" @endif
@if ($hasLainnyaOption) data-lainnya-select="{{ $detail->id }}" @endif
data-select-search="true"
required>
<option value="" disabled {{ $oldAnswer ? '' : 'selected' }}>Pilih jawaban</option>
@foreach ($options as $option)
@php
$optionLabel = is_scalar($option) ? (string) $option : '';
$isLainnya = stripos($optionLabel, 'lainnya') !== false;
$optionValue = $isLainnya && $oldOtherAnswer ? $oldOtherAnswer : $optionLabel;
$shouldSelect = $oldAnswer === $optionValue || ($isLainnya && $shouldForceLainnyaSelection);
@endphp
<option value="{{ $optionValue }}"
data-original-value="{{ $optionLabel }}"
@if ($isLainnya) data-lainnya-option="{{ $detail->id }}" @endif
{{ $shouldSelect ? 'selected' : '' }}>
{{ $optionLabel }}
</option>
@endforeach
@if ($type === 'option_with_other' && !$hasLainnyaOption)
<option value="Lainnya"
data-original-value="Lainnya"
data-lainnya-option="{{ $detail->id }}">
Lainnya
</option>
@endif
</select>
@if ($hasLainnyaOption)
<div class="lainnya-input {{ $showLainnya ? 'show' : '' }}" data-lainnya-wrapper="{{ $detail->id }}">
<input type="text" class="form-control form-control-sm mt-2"
name="jawaban_lainnya[{{ $detail->id }}]"
value="{{ $oldOtherAnswer }}"
data-field-hal="{{ $detailHal }}"
data-lainnya-input="{{ $detail->id }}"
@if ($isConsentQuestion) data-consent-input="1" @endif
placeholder="Tuliskan jawaban lainnya"
{{ $showLainnya ? 'required' : '' }}>
</div>
@endif
@else
@php
$lainnyaWrapperRendered = false;
@endphp
<div class="option-scroll">
@foreach ($options as $optionIndex => $option)
@php
$optionId = 'jawaban-' . $detail->id . '-' . $optionIndex;
$optionLabel = is_scalar($option) ? (string) $option : '';
$isLainnya = stripos($optionLabel, 'lainnya') !== false;
$optionValue = $isLainnya && $oldOtherAnswer ? $oldOtherAnswer : $optionLabel;
$shouldCheck = $oldAnswer === $optionValue || ($isLainnya && $shouldForceLainnyaSelection);
@endphp
<div class="form-check mb-2">
<input class="form-check-input @error('jawaban.' . $detail->id) is-invalid @enderror"
type="radio"
name="jawaban[{{ $detail->id }}]"
id="{{ $optionId }}"
value="{{ $optionValue }}"
data-original-value="{{ $optionLabel }}"
data-lainnya-radio="{{ $isLainnya ? $detail->id : '' }}" required
data-field-hal="{{ $detailHal }}"
@if ($isConsentQuestion) data-consent-input="1" @endif
{{ $shouldCheck ? 'checked' : '' }}>
<label class="form-check-label" for="{{ $optionId }}">
{{ $optionLabel }}
</label>
</div>
@if ($isLainnya)
@php
$lainnyaWrapperRendered = true;
@endphp
<div class="lainnya-input {{ $showLainnya ? 'show' : '' }}" data-lainnya-wrapper="{{ $detail->id }}">
<input type="text" class="form-control form-control-sm mt-2"
name="jawaban_lainnya[{{ $detail->id }}]"
value="{{ $oldOtherAnswer }}"
data-lainnya-input="{{ $detail->id }}"
data-field-hal="{{ $detailHal }}"
@if ($isConsentQuestion) data-consent-input="1" @endif
placeholder="Tuliskan jawaban lainnya"
{{ $showLainnya ? 'required' : '' }}>
</div>
@endif
@endforeach
</div>
@if (!$lainnyaWrapperRendered && $type === 'option_with_other')
<div class="lainnya-input {{ $showLainnya ? 'show' : '' }}" data-lainnya-wrapper="{{ $detail->id }}">
<input type="text" class="form-control form-control-sm mt-2"
name="jawaban_lainnya[{{ $detail->id }}]"
value="{{ $oldOtherAnswer }}"
data-lainnya-input="{{ $detail->id }}"
data-field-hal="{{ $detailHal }}"
@if ($isConsentQuestion) data-consent-input="1" @endif
placeholder="Tuliskan jawaban lainnya"
{{ $showLainnya ? 'required' : '' }}>
</div>
@endif
@endif
@else
<input type="text" class="form-control @error('jawaban.' . $detail->id) is-invalid @enderror"
name="jawaban[{{ $detail->id }}]" value="{{ old('jawaban.' . $detail->id) }}" required
data-field-hal="{{ $detailHal }}"
@if ($isConsentQuestion) data-consent-input="1" @endif
placeholder="Masukkan jawaban Anda">
@endif
@endif
@error('jawaban.' . $detail->id)
<div class="invalid-feedback d-block">{{ $message }}</div>
@enderror
@error('jawaban_lainnya.' . $detail->id)
<div class="text-danger small mt-1">{{ $message }}</div>
@enderror
</div>
</div>
</div>
@empty
<div class="alert alert-info">
Belum ada pertanyaan pada halaman ini.
</div>
@endforelse
@error('lms_mutu_soal_id')
<p class="text-danger mb-0">{{ $message }}</p>
@enderror
@error('jawaban')
<p class="text-danger mb-0">{{ $message }}</p>
@enderror
<div class="d-flex flex-column flex-md-row justify-content-between align-items-md-center mt-4 gap-3">
<div class="d-flex gap-2">
<button type="button"
class="btn btn-outline-secondary btn-prev-hal"
data-nav-control="prev"
{{ $halSebelumnya ? '' : 'disabled' }}>
&larr; Halaman Sebelumnya
</button>
<button type="button"
class="btn btn-outline-secondary btn-next-hal"
data-nav-control="next"
{{ $halBerikut ? '' : 'disabled' }}>
Halaman Berikutnya &rarr;
</button>
</div>
<button type="submit" class="btn btn-primary ms-md-auto"
data-final-submit="true"
style="{{ $isHalTerakhir ? '' : 'display: none;' }}"
{{ $soal->soalDetail->isEmpty() ? 'disabled' : '' }}>
Simpan Jawaban
</button>
</div>
</form>
</div>
</div>
</div>
@endsection
@section('custom_js')
<script src="{{ asset('vuexy/assets/vendor/libs/select2/select2.js') }}"></script>
<script>
document.addEventListener('DOMContentLoaded', function () {
const form = document.getElementById('form-soal');
if (!form) {
return;
}
let halList;
try {
halList = JSON.parse(form.dataset.halList || '[]');
} catch (error) {
halList = [];
}
if (!Array.isArray(halList) || !halList.length) {
halList = [parseInt(document.getElementById('input-hal')?.value || '1', 10) || 1];
}
halList = halList.map(function (value) {
return parseInt(value, 10);
});
const hiddenHalInput = document.getElementById('input-hal');
let currentHal = parseInt(hiddenHalInput?.value || halList[0], 10);
const navHalButtons = document.querySelectorAll('.nav-hal-btn');
const questionCards = document.querySelectorAll('[data-hal-card]');
const halInputs = document.querySelectorAll('[data-field-hal]');
const prevButton = document.querySelector('.btn-prev-hal');
const nextButton = document.querySelector('.btn-next-hal');
const finalSubmitButton = document.querySelector('[data-final-submit="true"]');
const badgeHal = document.getElementById('badge-hal');
const progressBar = document.getElementById('progress-bar');
const progressText = document.getElementById('progress-text');
const summaryHal = document.getElementById('summary-hal');
const totalHal = halList.length || 1;
const nonConsentFields = document.querySelectorAll('[data-field-hal]:not([data-consent-input="1"])');
const consentFields = document.querySelectorAll('[data-consent-input="1"]');
const headSoalCard = document.getElementById('head_soal');
const consentNegativeKeywords = ['tidak', 'tidak setuju'];
let immediateSubmitActive = false;
function normalizeOtherValue(value) {
return (value || '').toString().trim().toLowerCase();
}
function isOtherChoice(value) {
const normalized = normalizeOtherValue(value);
if (!normalized) {
return false;
}
return normalized === 'lainnya'
|| normalized === 'lainnya (sebutkan)'
|| normalized === 'lainnya/other'
|| normalized === 'lainnya / other'
|| normalized === 'other'
|| normalized === 'others'
|| normalized.includes('lainnya')
|| normalized.includes('other');
}
function getLabelTextByInput(input) {
if (!input || !input.id) {
return '';
}
const label = document.querySelector('label[for="' + input.id + '"]');
return label ? (label.textContent || '') : '';
}
halInputs.forEach(function (field) {
if (field.dataset && field.dataset.lainnyaInput) {
field.dataset.originalRequired = '0';
field.dataset.dynamicRequired = field.required ? '1' : '0';
} else {
field.dataset.originalRequired = field.required ? '1' : '0';
field.dataset.dynamicRequired = field.dataset.dynamicRequired || '0';
}
});
initSelectSearch();
setupLainnyaInputs();
setupDualFormInputs();
setupConsentWatcher();
updateQuestionVisibility();
updateNavigationUI();
navHalButtons.forEach(function (button) {
button.addEventListener('click', function () {
const targetHal = parseInt(button.dataset.navHal, 10);
changeHal(targetHal);
});
});
if (prevButton) {
prevButton.addEventListener('click', function () {
navigateRelative(-1);
});
}
if (nextButton) {
nextButton.addEventListener('click', function () {
navigateRelative(1);
});
}
form.addEventListener('submit', function () {
if (!immediateSubmitActive) {
return;
}
nonConsentFields.forEach(function (field) {
if (shouldDisableFieldForImmediate(field)) {
field.disabled = true;
}
});
});
function navigateRelative(step) {
if (immediateSubmitActive) {
return;
}
const currentIndex = halList.indexOf(currentHal);
const targetHal = halList[currentIndex + step];
if (typeof targetHal === 'undefined') {
return;
}
if (headSoalCard) {
if (targetHal === 1) {
headSoalCard.classList.remove('d-none');
} else {
headSoalCard.classList.add('d-none');
}
}
changeHal(targetHal);
}
function changeHal(targetHal) {
if (immediateSubmitActive) {
return;
}
if (targetHal === currentHal || halList.indexOf(targetHal) === -1) {
return;
}
const currentIndex = halList.indexOf(currentHal);
const targetIndex = halList.indexOf(targetHal);
const movingForward = targetIndex > currentIndex;
if (movingForward && !validateHal(currentHal)) {
return;
}
currentHal = targetHal;
if (hiddenHalInput) {
hiddenHalInput.value = currentHal;
}
updateQuestionVisibility();
updateNavigationUI();
}
function validateHal(halValue) {
const fieldsToDisable = [];
halInputs.forEach(function (field) {
const fieldHal = parseInt(field.dataset.fieldHal, 10);
if (fieldHal !== halValue && field.required) {
field.dataset.tmpRequired = '1';
field.required = false;
fieldsToDisable.push(field);
}
});
const isValid = form.checkValidity();
if (!isValid) {
form.reportValidity();
}
fieldsToDisable.forEach(function (field) {
field.required = true;
delete field.dataset.tmpRequired;
});
return isValid;
}
function updateQuestionVisibility() {
questionCards.forEach(function (card) {
const halValue = parseInt(card.dataset.halCard, 10);
card.style.display = halValue === currentHal ? '' : 'none';
});
}
function updateNavigationUI() {
const currentIndex = halList.indexOf(currentHal);
const isFirst = currentIndex <= 0;
const isLast = currentIndex === halList.length - 1;
if (prevButton) {
prevButton.disabled = immediateSubmitActive ? true : isFirst;
}
if (nextButton) {
if (immediateSubmitActive) {
nextButton.style.display = 'none';
} else {
nextButton.style.display = '';
nextButton.disabled = isLast;
}
}
navHalButtons.forEach(function (button) {
const isActive = parseInt(button.dataset.navHal, 10) === currentHal;
button.classList.toggle('btn-primary', isActive);
button.classList.toggle('btn-outline-primary', !isActive);
button.disabled = immediateSubmitActive;
});
const progress = totalHal > 0 ? Math.round(((currentIndex + 1) / totalHal) * 100) : 100;
if (badgeHal) {
badgeHal.textContent = 'Halaman ' + currentHal;
}
if (progressBar) {
progressBar.style.width = progress + '%';
progressBar.setAttribute('aria-valuenow', progress);
}
if (progressText) {
progressText.textContent = progress + '%';
}
if (summaryHal) {
summaryHal.textContent = 'Halaman ' + (currentIndex + 1) + ' dari ' + totalHal;
}
if (finalSubmitButton) {
finalSubmitButton.style.display = (isLast || immediateSubmitActive) ? '' : 'none';
}
}
function setupLainnyaInputs() {
document.querySelectorAll('input[type="radio"]').forEach(function (radio) {
radio.addEventListener('change', function (event) {
const customDetailId = event.target.getAttribute('data-lainnya-radio');
const detailId = customDetailId || event.target.name.replace('jawaban[', '').replace(']', '');
const targetWrapper = detailId ? document.querySelector('[data-lainnya-wrapper="' + detailId + '"]') : null;
const labelText = getLabelTextByInput(event.target);
const shouldShow = !!customDetailId
|| isOtherChoice(event.target.value)
|| isOtherChoice(event.target.dataset.originalValue)
|| isOtherChoice(labelText);
if (targetWrapper) {
if (shouldShow) {
handleLainnyaInput(targetWrapper, true);
} else {
handleLainnyaInput(targetWrapper, false, true);
}
}
});
});
document.querySelectorAll('[data-lainnya-input]').forEach(function (input) {
input.addEventListener('input', function (event) {
const detailId = input.getAttribute('data-lainnya-input');
syncCustomOptionValue(detailId, event.target.value);
});
});
document.querySelectorAll('[data-lainnya-select]').forEach(function (select) {
const detailId = select.name.replace('jawaban[', '').replace(']', '');
select.addEventListener('change', function (event) {
handleLainnyaSelect(event.target, detailId, true);
});
handleLainnyaSelect(select, detailId, false);
});
}
function handleLainnyaInput(wrapper, show, clearValue = false) {
if (!wrapper) {
return;
}
wrapper.classList.toggle('show', show);
const input = wrapper.querySelector('input');
const detailId = wrapper.getAttribute('data-lainnya-wrapper');
if (input) {
input.required = show;
input.dataset.dynamicRequired = show ? '1' : '0';
if (show) {
input.focus();
syncCustomOptionValue(detailId, input.value);
} else {
if (clearValue) {
input.value = '';
}
resetCustomOptionValue(detailId);
}
} else if (!show) {
resetCustomOptionValue(detailId);
}
}
function handleLainnyaSelect(selectElement, detailId, canClear) {
if (!selectElement || !detailId) {
return;
}
const targetWrapper = document.querySelector('[data-lainnya-wrapper="' + detailId + '"]');
if (!targetWrapper) {
return;
}
const selectedOption = selectElement.options[selectElement.selectedIndex];
const optionText = selectedOption ? (selectedOption.textContent || selectedOption.innerText || '') : '';
const originalValue = selectedOption ? (selectedOption.dataset.originalValue || '') : '';
const isLainnyaSelected = selectedOption && (
selectedOption.dataset.lainnyaOption
|| isOtherChoice(selectElement.value)
|| isOtherChoice(optionText)
|| isOtherChoice(originalValue)
);
if (isLainnyaSelected) {
handleLainnyaInput(targetWrapper, true);
} else {
handleLainnyaInput(targetWrapper, false, canClear);
}
}
function syncCustomOptionValue(detailId, customValue) {
if (!detailId) {
return;
}
const trimmedValue = (customValue || '').toString().trim();
const radio = document.querySelector('input[data-lainnya-radio="' + detailId + '"]');
if (radio) {
const originalValue = radio.dataset.originalValue || 'lainnya';
radio.value = trimmedValue || originalValue;
}
const select = document.querySelector('[data-lainnya-select="' + detailId + '"]');
if (select) {
const option = select.querySelector('[data-lainnya-option="' + detailId + '"]');
if (option) {
const originalOptionValue = option.dataset.originalValue || 'lainnya';
option.value = trimmedValue || originalOptionValue;
}
}
}
function resetCustomOptionValue(detailId) {
if (!detailId) {
return;
}
const radio = document.querySelector('input[data-lainnya-radio="' + detailId + '"]');
if (radio && radio.dataset.originalValue) {
radio.value = radio.dataset.originalValue;
}
const select = document.querySelector('[data-lainnya-select="' + detailId + '"]');
if (select) {
const option = select.querySelector('[data-lainnya-option="' + detailId + '"]');
if (option && option.dataset.originalValue) {
option.value = option.dataset.originalValue;
}
}
}
function shouldDisableFieldForImmediate(field) {
if (!field || field.dataset.consentInput === '1') {
return false;
}
const tagName = (field.tagName || '').toLowerCase();
const type = (field.type || '').toLowerCase();
if (type === 'radio' || type === 'checkbox') {
return false;
}
if (tagName === 'select') {
const value = field.value;
return value === null || value === '';
}
const value = (field.value || '').toString().trim();
return value === '';
}
function initSelectSearch() {
if (!window.jQuery || !window.jQuery.fn || typeof window.jQuery.fn.select2 === 'undefined') {
return;
}
const $ = window.jQuery;
$('[data-select-search="true"]').each(function () {
const $select = $(this);
if ($select.data('select2')) {
return;
}
$select.wrap('<div class="position-relative w-100"></div>');
$select.select2({
dropdownParent: $select.parent(),
width: '100%',
placeholder: $select.find('option[disabled]').first().text() || 'Pilih jawaban',
minimumResultsForSearch: 0
});
if ($select.is('[data-lainnya-select]')) {
const detailId = ($select.attr('name') || '').replace('jawaban[', '').replace(']', '');
$select.on('select2:select', function () {
handleLainnyaSelect(this, detailId, true);
});
}
});
}
function setupDualFormInputs() {
document.querySelectorAll('[data-dual-wrapper]').forEach(function (wrapper) {
const detailId = wrapper.getAttribute('data-dual-wrapper');
const hiddenInput = wrapper.querySelector('[data-dual-hidden]');
const yearInput = wrapper.querySelector('[data-dual-input="tahun"]');
const monthInput = wrapper.querySelector('[data-dual-input="bulan"]');
const inputs = [yearInput, monthInput].filter(Boolean);
inputs.forEach(function (input) {
input.addEventListener('input', function () {
updateDualFormAnswer(detailId);
});
});
updateDualFormAnswer(detailId);
});
}
function updateDualFormAnswer(detailId) {
if (!detailId) {
return;
}
const wrapper = document.querySelector('[data-dual-wrapper="' + detailId + '"]');
if (!wrapper) {
return;
}
const hiddenInput = wrapper.querySelector('[data-dual-hidden]');
if (!hiddenInput) {
return;
}
const yearInput = wrapper.querySelector('[data-dual-input="tahun"]');
const monthInput = wrapper.querySelector('[data-dual-input="bulan"]');
const yearValue = (yearInput && yearInput.value ? yearInput.value : '').toString().trim();
const monthValue = (monthInput && monthInput.value ? monthInput.value : '').toString().trim();
const parts = [];
if (yearValue !== '') {
parts.push(yearValue + ' (Tahun)');
}
if (monthValue !== '') {
parts.push(monthValue + ' (Bulan)');
}
const combined = parts.join(' ');
hiddenInput.value = combined;
if (hiddenInput.required) {
hiddenInput.setCustomValidity(combined ? '' : 'Harap isi minimal salah satu kolom (Tahun/Bulan).');
}
}
function setupConsentWatcher() {
if (!consentFields.length) {
return;
}
consentFields.forEach(function (field) {
field.addEventListener('change', function (event) {
if (field.type === 'radio' && !field.checked) {
return;
}
evaluateConsentValue(event.target.value);
});
if (
(field.type === 'radio' && field.checked) ||
(field.tagName === 'SELECT' && field.value) ||
(field.type !== 'radio' && field.value)
) {
evaluateConsentValue(field.value);
}
});
}
function evaluateConsentValue(value) {
const normalized = (value || '').toString().trim().toLowerCase();
const shouldStop = consentNegativeKeywords.some(function (keyword) {
return normalized.startsWith(keyword);
});
toggleImmediateSubmit(shouldStop);
}
function toggleImmediateSubmit(activate) {
if (immediateSubmitActive === activate) {
updateNavigationUI();
return;
}
immediateSubmitActive = activate;
halInputs.forEach(function (field) {
const originalRequired = field.dataset.originalRequired === '1';
const dynamicRequired = field.dataset.dynamicRequired === '1';
field.required = activate ? false : (originalRequired || dynamicRequired);
if (!field.required && typeof field.setCustomValidity === 'function') {
field.setCustomValidity('');
}
});
updateNavigationUI();
}
});
</script>
@endsection