Skip to content

Commit

Permalink
When updating the value of a <select> to null or "" when there's a ca…
Browse files Browse the repository at this point in the history
…ption, make sure the selection doesn't get reset to the original value. Also make the "workaround for IE 6" only run on IE6.
  • Loading branch information
mbest committed Apr 9, 2017
1 parent 79d3f5f commit bd6e508
Show file tree
Hide file tree
Showing 3 changed files with 14 additions and 10 deletions.
5 changes: 5 additions & 0 deletions spec/defaultBindings/valueBehaviors.js
Expand Up @@ -360,6 +360,11 @@ describe('Binding: Value', function() {
observable("");
expect(testNode.childNodes[0].selectedIndex).toEqual(0);

// Also check that the selection doesn't change later (see https://github.com/knockout/knockout/issues/2218)
waits(10);
runs(function() {
expect(testNode.childNodes[0].selectedIndex).toEqual(0);
});
});

it('Should display the caption when the model value changes to undefined, null, or \"\" when options specified directly', function() {
Expand Down
11 changes: 1 addition & 10 deletions src/binding/defaultBindings/value.js
Expand Up @@ -94,20 +94,11 @@ ko.bindingHandlers['value'] = {
if (valueHasChanged) {
if (tagName === "select") {
var allowUnset = allBindings.get('valueAllowUnset');
var applyValueAction = function () {
ko.selectExtensions.writeValue(element, newValue, allowUnset);
};
applyValueAction();

ko.selectExtensions.writeValue(element, newValue, allowUnset);
if (!allowUnset && newValue !== ko.selectExtensions.readValue(element)) {
// If you try to set a model value that can't be represented in an already-populated dropdown, reject that change,
// because you're not allowed to have a model value that disagrees with a visible UI selection.
ko.dependencyDetection.ignore(ko.utils.triggerEvent, null, [element, "change"]);
} else {
// Workaround for IE6 bug: It won't reliably apply values to SELECT nodes during the same execution thread
// right after you've changed the set of OPTION nodes on it. So for that node type, we'll schedule a second thread
// to apply the value as well.
ko.utils.setTimeout(applyValueAction, 0);
}
} else {
ko.selectExtensions.writeValue(element, newValue);
Expand Down
8 changes: 8 additions & 0 deletions src/binding/selectExtensions.js
Expand Up @@ -55,6 +55,14 @@
}
if (allowUnset || selection >= 0 || (value === undefined && element.size > 1)) {
element.selectedIndex = selection;
if (ko.utils.ieVersion === 6) {
// Workaround for IE6 bug: It won't reliably apply values to SELECT nodes during the same execution thread
// right after you've changed the set of OPTION nodes on it. So for that node type, we'll schedule a second thread
// to apply the value as well.
ko.utils.setTimeout(function () {
element.selectedIndex = selection;
}, 0);
}
}
break;
default:
Expand Down

0 comments on commit bd6e508

Please sign in to comment.