Skip to content

Instantly share code, notes, and snippets.

@matsubo
Last active December 16, 2023 16:44
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save matsubo/c950963849bf27d262379fd723f5dabd to your computer and use it in GitHub Desktop.
Save matsubo/c950963849bf27d262379fd723f5dabd to your computer and use it in GitHub Desktop.
document.getElementById('postcode').addEventListener('keyup', function(e) {
if (!e.key.match(/[0-9]/)) return;
const postcode = e.target.value;
if (postcode.length !== 7) return;
const url = `https://postcode.teraren.com/postcodes/${postcode}.json`;
fetch(url)
.then(response => response.json())
.then(json => {
document.getElementById('prefecture').value = json.prefecture;
document.getElementById('city').value = json.city;
document.getElementById('suburb').value = json.suburb;
})
.catch(error => {
console.error(error);
['prefecture', 'city', 'suburb'].forEach(id => {
document.getElementById(id).value = '';
});
});
});
<form>
<input type="text" id="postcode" placeholder="1600023" maxlength="7" autofocus>
<input type="text" id="prefecture" placeholder="東京都" disabled>
<input type="text" id="city" placeholder="新宿区" disabled>
<input type="text" id="suburb" placeholder="西新宿" disabled>
</form>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment