问题
Title pretty much says it all.
I have several select boxes on a page, all dynamically generated in an ASP.NET webform, some with hundreds of options. I'd like to be able to type in a search string and then select all entries that match.
It's easy to select all and deselect all using javascript on the base select control and then calling $('#control-id').trigger('chosen:update');
but I am having issues when trying to only select the options matching the search filter.
I'm not picky as to how this is done, either with a "Select all" option, an extra button, or a keystroke. This is for a backend dev-only page, so the UI doesn't have to be 100% intuitive.
回答1:
I ended up solving this by altering the chosen plugin and adding the following code to AbstractChosen.prototype.keyup_checker
:
case 65:
if (evt.ctrlKey && this.results_showing) {
if (typeof onSelectAll == 'function') {
onSelectAll($(this.container).attr('id'), $(this.form_field).attr('id'));
this.results_hide();
}
return true;
}
Basically, if Ctrl-A is pressed while the Chosen select is open, it will call a user-defined delegate onSelectAll
with the Chosen container's id and the underlying select's id as arguments. If the Ctrl key is not pressed, I want this to fall through to the default, which allows search string entry to work as usual.
Back on my page I have the following:
function onSelectAll(containerId, selectId) {
var ids = [];
$("#" + containerId).find('.active-result').each(function () { ids.push(parseInt($(this).attr('data-option-array-index'))); });
$(ids).each(function () { $($('#' + selectId + ' option')[this]).attr('selected', 'selected'); });
$('#' + selectId).trigger('chosen:updated');
}
This gets the array indexes of the visible results in the Chosen container, marks them as selected in the underlying select control, and then causes the Chosen container to update.
I am aware it's not entirely kosher to change the meaning of a standard keyboard shortcut, but in an informal poll of the three other devs most likely to actually use this thing, they all suggested it, so I think I'm in the clear for now. That said, suggestions to improve and clean up my javascript are quite welcome - I've been doing backend and SQL stuff for so long I've totally lost my UI chops.
来源:https://stackoverflow.com/questions/23157212/how-do-i-select-all-options-in-a-jquery-chosen-multi-select-after-search-filteri