コピペで使える郵便番号自動入力
都道府県はセレクトボックス
他はテキストボックスというよくある郵便番号住所入力機能
実装は10分、ChatGPTくんとの合作
要素選択のID名を変更すればそのまま使えます
async function getAddress() {
const zip_label = document.getElementById('zip_label'); // 郵便番号フォームのラベル
const zipcode = document.getElementById('zip').value; // 郵便番号テキストボックス
const prefOptions = document.getElementById('pref_id').options; // 都道府県の選択肢メニュー
const city = document.getElementById('city') // 市町村 テキストボックス
const town = document.getElementById('town') // 街名 テキストボックス
const url = `https://zipcloud.ibsnet.co.jp/api/search?zipcode=${zipcode}`;
zip_label.innerHTML = '郵便番号'
try {
const response = await fetch(url);
if (!response.ok) { throw new Error('通信エラーが発生しました'); }
const data = await response.json();
if (data.status !== 200) { throw new Error('該当する住所がありません'); }
const prefName = data.results[0].address1;
const option = Array.from(prefOptions).find((opt) => opt.text.includes(prefName));
if (option) { option.selected = true; }
city.value = data.results[0].address2;
town.value = data.results[0].address3;
zip_label.innerHTML = '郵便番号 (' + prefName + city.value + town.value + ')';
} catch (error) {
if (error.message.indexOf('null')) { error.message = '該当の住所が見つかりませんでした' }
zip_label.innerHTML = '郵便番号 (' + error.message + ')';
}
}