0
0

More than 1 year has passed since last update.

コピペで使える郵便番号自動入力機能をChatGPTと作った

Last updated at Posted at 2023-02-16

コピペで使える郵便番号自動入力

都道府県はセレクトボックス
他はテキストボックスというよくある郵便番号住所入力機能

実装は10分、ChatGPTくんとの合作
要素選択のID名を変更すればそのまま使えます

image.png

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 + ')';
  }
}
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0