補完が手入力と衝突する場面を知る
最後に電話番号を入れたところ、ほかの欄まで上書きされたという報告。自動入力が変更してよい範囲を考える材料に。
手入力した欄を補完から守る
元の実例の着眼点を試すための独自のWebサンプルです。
部署だけ自分で入力して「候補を反映」を押し、部署名が残ることを確かめてください。
実装の手順
- 自動候補を受け取る欄ごとに、利用者が編集したかどうかを記録する。
- 自動候補は未編集かつ空欄の項目だけに適用する。手で消した項目も編集済みとして扱う。
- フォームの実装では値に加えて編集状態も保持し、非同期の候補が遅れて届く場合も適用直前に判定する。
動作確認
書き換えた欄も、手で空に戻した欄も再度上書きされない。
サンプルコードを見る
<!doctype html>
<html lang="ja">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>手入力した欄を補完から守る</title>
<style>
* { box-sizing: border-box; }
body {
margin: 0;
padding: 16px;
background: #23232a;
color: #f4f0ea;
font: 16px/1.6 system-ui, sans-serif;
}
label, output, strong, audio, progress { display: block; margin: 6px 0; }
input, select, button { max-width: 100%; font: inherit; }
input, select { padding: 4px 7px; }
button {
margin: 4px 0;
padding: 5px 12px;
cursor: pointer;
border: 1px solid #b5a399;
border-radius: 6px;
}
:focus-visible { outline: 3px solid #ffad73; outline-offset: 2px; }
audio { width: 100%; }
[hidden] { display: none !important; }
</style>
</head>
<body>
<label>部署 <input id="team"></label>
<label>拠点 <input id="office"></label>
<button id="apply">候補を反映</button>
<output id="result"></output>
<script>
const suggestions = { team: '企画', office: '東京' };
const edited = new Set();
for (const id of Object.keys(suggestions)) {
document.getElementById(id).oninput = () => edited.add(id);
}
document.querySelector('#apply').onclick = () => {
let count = 0;
for (const [id, value] of Object.entries(suggestions)) {
const input = document.getElementById(id);
if (!edited.has(id) && !input.value) {
input.value = value;
count++;
}
}
document.querySelector('#result').textContent = count + '件に候補を反映しました';
};
</script>
</body>
</html>index.html に保存し、ブラウザで開くと試せます。