Last active
May 26, 2022 23:48
-
-
Save takunagai/28979a23115d743e2c42acd3dfcc7ad2 to your computer and use it in GitHub Desktop.
[郵便番号から住所を取得] Get address from Japanese zip code #JavaScript
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// npm install yubinbango.js | |
import YubinBango from "yubinbango.js"; | |
/** | |
* 郵便番号から住所を自動入力 (複数フォーム、複数の住所対応) | |
* @param {string} wrapper 包括する要素(クラスで指定) | |
* @param {string} postalCodeInput 郵便番号入力フォーム(クラスで指定) | |
* @param {string} addressInput 住所入力フォーム(自動入力される。クラスで指定) | |
* @see https://github.com/arayaryoma/yubinbango.js | |
*/ | |
function postalCodeToAddress( | |
wrapper = "h-adr", | |
postalCodeInput = "p-postal-code", | |
addressInput = "p-extended-address" | |
) { | |
const formElms = document.getElementsByClassName(wrapper); | |
for (let i = 0, len = formElms.length | 0; i < len; i = (i + 1) | 0) { | |
const postalCodes = formElms[i].getElementsByClassName(postalCodeInput), | |
addressValues = formElms[i].getElementsByClassName(addressInput); | |
for (let i = 0, len = postalCodes.length | 0; i < len; i = (i + 1) | 0) { | |
const postalCode = postalCodes[i]; | |
postalCode.onchange = function () { | |
YubinBango.getAddress(postalCode.value).then((res) => { | |
addressValues[i].value = `${res.prefecture}${res.locality}${res.street}`; | |
}); | |
}; | |
} | |
} | |
} | |
postalCodeToAddress(); // default: 'h-adr', 'p-postal-code', 'p-extended-address' |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<div class="h-adr wp-block-contact-form-7-contact-form-selector"> | |
<form action="" method="post"> | |
<span class="p-country-name" style="display:none;">Japan</span> | |
<p><label><b>郵便番号</b><br> | |
<input type="text" class="p-postal-code" size="16" value=""></label></p> | |
<p><label><b>ご住所</b><br> | |
<input type="text" class="p-extended-address" size="40" value=""></label></p> | |
<p><input type="submit" value="送信する"></p> | |
</form> | |
</div> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment