请求为combo-select脚本添加失焦/提交时选中高亮选项功能
Hey there! I totally get why you're sticking with combo-select—it's lightweight and does the job without all the bloat of bigger libraries like Select2 or Selectize. Let's fix that issue where it auto-selects matching options when you type numbers but not text, and get it to pick the closest highlighted option on blur or form submit.
The Problem
The default combo-select behavior only triggers the auto-select logic for numeric input, and the autoFocus parameter you tried doesn't handle this specific blur/submit scenario—it's meant for something else entirely.
The Solution
We'll add custom event listeners to catch when the input loses focus or the form submits, then manually set the select value to the highlighted option if one exists. Here's the code:
$(function(){ // Initialize combo-select as usual $('select').comboSelect(); // Handle input blur event $('.combo-select-input').on('blur', function() { const $comboContainer = $(this).closest('.combo-select'); const $highlightedOption = $comboContainer.find('.combo-select-option.highlighted'); // If there's a highlighted option, update the select and input if ($highlightedOption.length) { const optionValue = $highlightedOption.data('value'); const optionText = $highlightedOption.text(); // Update the hidden select element's value $comboContainer.find('select').val(optionValue); // Update the visible input's display text $(this).val(optionText); } }); // Handle form submit to ensure the correct value is sent $('form').on('submit', function() { $('.combo-select-input').each(function() { const $comboContainer = $(this).closest('.combo-select'); const $highlightedOption = $comboContainer.find('.combo-select-option.highlighted'); if ($highlightedOption.length) { const optionValue = $highlightedOption.data('value'); $comboContainer.find('select').val(optionValue); } }); }); });
How This Works
- Blur Event Handling: When the combo-select input loses focus, we look for the option with the
highlightedclass (this is the one that's visually highlighted as you type). If found, we update both the hidden underlying<select>element (so the correct value is sent with the form) and the visible input text. - Form Submit Handling: We loop through all combo-select inputs on form submit to make sure even if the user didn't blur the input before submitting, the highlighted option's value is set on the hidden select.
Notes
- If you've customized the class names in your combo-select configuration, adjust the selectors (
.combo-select,.combo-select-input,.combo-select-option) to match your custom classes. - Test this by typing text that matches part of an option—once the desired option is highlighted, click outside the input or submit the form, and it should auto-select that option.
内容的提问来源于stack exchange,提问作者Joe Landry

