页面PNR输入框无法启用Autocomplete功能的技术咨询
Let's tackle this PNR autocomplete issue step by step. The problem likely stems from your onkeypress event interfering with the browser's autocomplete behavior, plus a missing autocomplete attribute to explicitly enable the feature. Here's how to fix it:
1. Add the autocomplete attribute
First, make sure your input explicitly tells the browser to enable autocomplete. You can use a custom value like "pnr" (since PNR isn't a standard autocomplete field, but browsers will still respect it) or just "on":
<input class="form-control_custom input_text_custom" type="text" id="inputPnrNo" maxlength="10" value="" placeholder="Enter PNR No." autocomplete="pnr">
2. Replace onkeypress with an input event handler
Your original onkeypress logic blocks any key that isn't a number (or has a charCode of 0). This can prevent the browser from pasting/filling autocomplete values, since those actions might trigger events that don't match your charCode check. Instead, use an input event to filter the input after it's entered—this keeps your number restriction while letting autocomplete work:
<input class="form-control_custom input_text_custom" type="text" id="inputPnrNo" maxlength="10" value="" placeholder="Enter PNR No." autocomplete="pnr" oninput="filterPnrInput(this)">
Then add this JavaScript function (you can put it in a <script> tag or your external JS file):
function filterPnrInput(input) { // Remove any non-numeric characters input.value = input.value.replace(/[^0-9]/g, ''); // Enforce max length of 10 if (input.value.length > 10) { input.value = input.value.slice(0, 10); } }
Why this works
- The
autocompleteattribute signals to the browser that it should offer saved values for this field. - Using
oninputinstead ofonkeypressavoids blocking the browser's default autocomplete actions. We're just cleaning up the input after it's been entered, not preventing the input from happening in the first place.
Quick checks
- Make sure your browser has autocomplete enabled (most do by default, but double-check settings if needed).
- If your input is inside a
<form>tag, ensure the form doesn't haveautocomplete="off"set (this would override the input's setting).
内容的提问来源于stack exchange,提问作者user5858

