Last active
December 16, 2023 16:44
-
-
Save matsubo/c950963849bf27d262379fd723f5dabd to your computer and use it in GitHub Desktop.
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
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 = ''; | |
}); | |
}); | |
}); |
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
<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