MDL-73213 autocomplete: keep selected value when the state changes.

The selected value of the dropdown was being cleared when the dropdown
was opened, this was causing an error when submitting the form if the
field was required. The main cause was that we were emptying the
select before loading new values, this solution was created because
of an issue where we could not deselect values if the list was
reloaded. To fix this problem, I added an empty option as the first
element of the select only when deselecting a certain item.
This commit is contained in:
Pedro Jordao 2023-07-06 14:52:18 -03:00
parent 6628845087
commit 2ace3d54dc
4 changed files with 27 additions and 6 deletions

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

View File

@ -239,6 +239,9 @@ define([
var deselectItem = function(options, state, item, originalSelect) {
var selectedItemValue = $(item).attr('data-value');
// Preprend an empty option to the select list to avoid having a default selected option.
originalSelect.prepend($('<option>'));
// Look for a match, and toggle the selected property if there is a match.
originalSelect.children('option').each(function(index, ele) {
if ($(ele).attr('value') == selectedItemValue) {
@ -655,10 +658,7 @@ define([
var processedResults = ajaxHandler.processResults(options.selector, results);
var existingValues = [];
// Now destroy all options that are not currently selected.
if (!options.multiple) {
originalSelect.children('option').remove();
}
// Now destroy all options that are not current
originalSelect.children('option').each(function(optionIndex, option) {
option = $(option);
if (!option.prop('selected')) {

View File

@ -62,3 +62,24 @@ Feature: Autocomplete functionality in forms
And I click on "Course 1" "autocomplete_selection"
And the "Single select will be enabled if the control is blank" "field" should be enabled
And the "Single select will be disabled if the control is blank" "field" should be disabled
@javascript
Scenario: Single-select autocomplete can be cleared after being set and suggestion list reloaded
Given the following "users" exist:
| username | firstname | lastname |
| user1 | Jane | Jones |
| user2 | Sam | Smith |
| user3 | Mark | Davis |
And I log in as "admin"
When I navigate to "Server > Web services > Manage tokens" in site administration
And I press "Create token"
And I open the autocomplete suggestions list
And I click on "Jane Jones" item in the autocomplete list
Then "Jane Jones" "autocomplete_selection" should exist
# Only reload de sugestion list
And I open the autocomplete suggestions list
# Remove selection
And I click on "Jane Jones" "autocomplete_selection"
And "Jane Jones" "autocomplete_selection" should not exist
And I should see "No selection" in the ".form-autocomplete-selection" "css_element"