如何为支持自定义输入的jQuery Chosen多选框添加自动格式化功能
解决方案
问题核心
jQuery Chosen 初始化后会隐藏原生的 <select> 元素,用户实际输入内容的是组件动态生成的搜索输入框,你之前将格式化事件绑定到原生 select 上自然不会生效。
正确的绑定目标选择器为:#num + .chosen-container .search-field input[type=text]
修改后完整代码
仅需要替换你原有 JavaScript 中绑定到 #num 的 keydown 事件部分即可,其余逻辑无需改动:
// 先初始化Chosen $('.chosen-select').chosen({}).change( function(obj, result) { console.debug("changed: %o", arguments); console.log("selected: " + result.selected); }); // 绑定格式化事件到Chosen的动态搜索输入框 // 用委托模式适配多选场景下搜索框动态重建的情况 $(document).on('keydown', '#num ~ .chosen-container .search-field input', function (e) { var key = e.charCode || e.keyCode || 0; $text = $(this); if (key !== 8 && key !== 9) { if ($text.val().length === 1) { $text.val($text.val() + '-'); } if ($text.val().length === 3) { $text.val($text.val() + '-'); } if ($text.val().length === 7) { $text.val($text.val() + ':'); } if ($text.val().length === 12) { $text.val($text.val() + ' ZIO '); } } return (key == 8 || key == 9 || key == 46 || (key >= 48 && key <= 57) || (key >= 96 && key <= 105)); }) // 原有自定义添加逻辑保留 $(function (){ $("#num").on("chosen:no_results", function (evt, params) { let elem = $("#num").siblings(".chosen-container").find(".chosen-choices .search-field:last input"); let text = elem.val().replace(/'/g, ""); text = `<button class="btn btn-success" onClick="addCustomNum('${text}')" style="height: 30px; font-size: 15px;">Add NEW TMK: '${text}'</button>`; $("#num").siblings(".chosen-container").find(".no-results").html(text); }); }); function addCustomNum(searchStr) { let arr = $("#num").val(); $("#num").html($("#num").html() + "<option value='" + searchStr + "'>" + searchStr + "</option>"); $("#num").val(arr.concat([searchStr])); $("#num").trigger("chosen:updated"); } // 原有普通输入框逻辑保留 $(function () { $('#num_no_jqc').keydown(function (e) { var key = e.charCode || e.keyCode || 0; $text = $(this); if (key !== 8 && key !== 9) { if ($text.val().length === 1) { $text.val($text.val() + '-'); } if ($text.val().length === 3) { $text.val($text.val() + '-'); } if ($text.val().length === 7) { $text.val($text.val() + ':'); } if ($text.val().length === 12) { $text.val($text.val() + ' ZIO '); } } return (key == 8 || key == 9 || key == 46 || (key >= 48 && key <= 57) || (key >= 96 && key <= 105)); }) });
验证效果
修改完成后,用户在Chosen输入框输入数字时,会自动按照你要求的规则格式化,输入12142113114444将自动输出1-2-1421:1311 ZIO 4444,点击添加按钮可将格式化后的内容新增为选项。
内容的提问来源于stack exchange,提问作者gabe-aeth
相关产品推荐
相关产品推荐

