
当使用 Chosen.js(class="chzn-select")增强 元素时,原生 autofocus 属性会失效;需通过 JavaScript 在 DOM 加载完成后手动调用 focus() 方法实现焦点自动获取。
当使用 chosen.js(`class="chzn-select"`)增强 `
Chosen.js 是一款广泛使用的 jQuery 下拉增强插件,它将原生
✅ 正确解决方案:延迟聚焦 + 显式 ID 引用
你需要为
以下是完整、可直接部署的修复代码示例:
<!-- 引入 jQuery 和 Chosen.js(务必在 script 前加载) -->
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/chosen/1.8.7/chosen.min.css">
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/chosen/1.8.7/chosen.jquery.min.js"></script>
<form action="incoming.php" method="post">
<input type="hidden" name="pt" value="<?php echo htmlspecialchars($_GET['id']); ?>">
<input type="hidden" name="invoice" value="<?php echo htmlspecialchars($_GET['invoice']); ?>">
<!-- ✅ 关键:添加 id 并移除 autofocus(由 JS 控制) -->
<select name="product" id="product"
onchange="handleSelectionChange(this, document.querySelector('[name=qty]'))"
class="chzn-select"
style="width:300px;"
required>
<option value=""></option>
<?php
try {
include('../connect.php');
$result = $db->prepare("SELECT * FROM products");
$result->execute();
while ($row = $result->fetch()) {
echo '<option value="' . htmlspecialchars($row['product_id']) . '">'
. htmlspecialchars($row['product_code']) . ' - '
. htmlspecialchars($row['gen_name']) . ' - '
. htmlspecialchars($row['product_name']) . ' | Expires at: '
. htmlspecialchars($row['expiry_date']) . '</option>';
}
} catch (PDOException $e) {
echo '<option disabled>Error loading products</option>';
}
?>
</select>
<input type="number"
name="qty"
onkeydown="handleKeyPress(event, this, document.querySelector('[name=price1]'))"
min="1"
placeholder="Qty"
autocomplete="off"
style="width:300px; height:30px; padding:6px 0 4px; margin-right:4px; font-size:15px;"
required>
<input type="hidden" name="discount" value="" autocomplete="off" style="width:68px; height:30px; padding:6px 0 4px; margin-right:4px; font-size:15px;">
<input type="number"
name="price1"
onkeydown="handleKeyPress(event, this, document.querySelector('button[name=button]'))"
placeholder="Price"
autocomplete="off"
style="width:300px; height:30px; padding:6px 0 4px; margin-right:4px; font-size:15px;"
required>
<input type="hidden" name="date" value="<?php echo date('m/d/y'); ?>">
<button type="submit" name="button" class="btn btn-info" style="width:123px; height:35px; margin-top:-5px;">
<i class="icon-plus-sign icon-large"></i> Add
</button>
</form>
<script>
// ✅ 确保在 Chosen 初始化完成后再聚焦(推荐方式)
document.addEventListener('DOMContentLoaded', function() {
// 初始化 Chosen(若尚未初始化)
$('.chzn-select').chosen({
width: '300px',
no_results_text: 'No matches found'
});
// 延迟 100ms 确保 Chosen 渲染完毕,再聚焦到可见容器
setTimeout(() => {
const chosenContainer = document.querySelector('.chzn-container');
if (chosenContainer) {
const searchField = chosenContainer.querySelector('.chzn-search input');
if (searchField) searchField.focus();
}
}, 100);
});
// 原有业务逻辑函数(已优化参数传递方式,避免全局变量依赖)
function handleSelectionChange(selectElement, nextField) {
if (nextField && typeof nextField.focus === 'function') {
nextField.focus();
}
}
function handleKeyPress(event, currentField, nextField) {
if (event.key === "Enter") {
event.preventDefault();
if (nextField && typeof nextField.focus === 'function') {
nextField.focus();
}
}
}
</script>⚠️ 关键注意事项:
- 不要依赖 autofocus 属性:Chosen 会禁用原生行为,强行保留会导致不可预测结果;
-
聚焦目标应为 Chosen 的搜索输入框(.chzn-search input),而非原始
,这才是用户实际交互的焦点区域; - 务必检查 Chosen 初始化时机:若页面中存在多个 Chosen 实例或动态加载内容,需确保 chosen() 已执行完毕再聚焦;
- 安全加固:PHP 输出内容必须经 htmlspecialchars() 过滤,防止 XSS;数据库查询建议使用预处理语句绑定参数(当前已使用,值得肯定);
- 无障碍兼容性:Chosen 默认支持键盘导航(Tab/Arrow/Enter),聚焦后用户可直接键入搜索,符合 WCAG 标准。
通过以上方案,你不仅能彻底解决 autofocus 失效问题,还能提升表单的可用性与健壮性。对于复杂表单场景,还可进一步封装为通用 focusChosen(id) 函数,实现复用。










