<div class="container">
<form class="h-adr">
<span class="p-country-name" style="display:none;">Japan</span>
〒<input type="text" class="p-postal-code" size="8" maxlength="8">
<button type="button" class="postal-search">住所を検索する</button>
<label>住所
<input type="text" class="p-region p-locality p-street-address p-extended-address" />
</label>
</form>
</div>
.container {
margin: 30px;
}
label {
display: block;
}
input {
font-size: 16px;
margin-bottom: 15px;
}
.postal-search {
font-size: 16px;
}
.p-region {
display: inline-block;
width: 250px;
}
//該当フォーム
const hadr = document.querySelector(".h-adr");
let cancelFlag = true;
//イベントをキャンセルするリスナ
const onKeyupCanceller = function (e) {
if (cancelFlag) {
e.stopImmediatePropagation();
}
return false;
};
// 郵便番号の入力欄
const postalcode = hadr.querySelectorAll(".p-postal-code"),
postalField = postalcode[postalcode.length - 1];
//通常の挙動をキャンセルできるようにイベントを追加
postalField.addEventListener("keyup", onKeyupCanceller, false);
//ボタンクリック時
const btn = hadr.querySelector(".postal-search");
btn.addEventListener("click", function (e) {
//キャンセルを解除
cancelFlag = false;
//発火
let event;
if (typeof Event === "function") {
event = new Event("keyup");
} else {
event = document.createEvent("Event");
event.initEvent("keyup", true, true);
}
postalField.dispatchEvent(event);
//キャンセルを戻す
cancelFlag = true;
});
This Pen doesn't use any external CSS resources.