JavaScript: 動的な選択候補の絞り込み(2)

取り敢えず、スイッチの操作部種別を選んだら、それに対応する極数の候補を動的に絞り込むというJavaScriptのコードをChatGPT4oに作らせ動きました。最初は絞り込みの対応関係をJSONで書いてそれを読み込ませようとしたのですが、上手く動かないので結局元のHTML(blade)ファイルの中に書込む形になりました。あまり綺麗ではありませんが。しかしなかなか大変。書店でJavaScriptの本を何冊か立ち読みしてみましたが、現在選択されている候補を取得するとか、逆に候補を設定するとかはありましたが、動的な絞り込みまで載っている本は見つけられませんでした。
=========================================
<script>
document.addEventListener(‘DOMContentLoaded’, function() {
const switchOpPartSelect = document.querySelector(‘select[name=”switch_op_part_id”]’);
const switchPoleSelect = document.querySelector(‘select[name=”switch_pole_id”]’);

const allPoleOptions = [
@foreach ($switch_poles as $switch_pole)
{ id: “{{ $switch_pole->id }}”, text: “{{ $switch_pole->poles_number }}” },
@endforeach
];

switchOpPartSelect.addEventListener(‘change’, function() {
const selectedOpPartId = parseInt(this.value);
let filteredPoleOptions = [{ id: “1”, text: “-” }];

if ([2, 3, 5, 6].includes(selectedOpPartId)) {
filteredPoleOptions = filteredPoleOptions.concat(allPoleOptions.filter(option => [11, 12, 13, 14].includes(parseInt(option.id))));
} else if (selectedOpPartId === 4) {
filteredPoleOptions = filteredPoleOptions.concat(allPoleOptions.filter(option => [11, 12].includes(parseInt(option.id))));
} else if (selectedOpPartId === 7) {
filteredPoleOptions = [{ id: “1”, text: “-” }].concat(allPoleOptions);
} else {
filteredPoleOptions = [{ id: “1”, text: “-” }].concat(allPoleOptions);
}

switchPoleSelect.innerHTML = ”;
filteredPoleOptions.forEach(option => {
const newOption = document.createElement(‘option’);
newOption.value = option.id;
newOption.textContent = option.text;
switchPoleSelect.appendChild(newOption);
});
});

document.querySelector(‘form’).addEventListener(‘submit’, function() {
showLoadingMessage();
});

window.resetForm = function() {
document.querySelectorAll(‘select’).forEach(select => {
select.selectedIndex = 0;
});
document.querySelector(‘input[name=”type_name”]’).value = ”;

switchPoleSelect.innerHTML = ”;
[{ id: “1”, text: “-” }].concat(allPoleOptions).forEach(option => {
const newOption = document.createElement(‘option’);
newOption.value = option.id;
newOption.textContent = option.text;
switchPoleSelect.appendChild(newOption);
});
}
});

function showLoadingMessage() {
document.getElementById(‘loading-message’).style.display = ‘block’;
document.body.classList.add(‘loading’);
}
</script>

コメントを残す

メールアドレスが公開されることはありません。 が付いている欄は必須項目です

CAPTCHA