11

I have an input text box bound to a knockout js observable.

<input id="searchTextBox" class="searchTextBox" type="text" maxlength="25"
       title="Search" placeholder="Search"
       data-bind="value: GridVm.FilterText,
       valueUpdate: 'afterkeydown',
       disable: GridVm.Data().length == 0" />

The problem is that the FilterText observable doesn't update when the user clicks the x in IE.

I've found that I can remove the x (see the screen shot in the linked question), but that's a last resort (I like the feature). This forum says there is no event fired when the x is clicked.

Is there an event that I can use to force a Knockout observable update or a good way to do this in Knockout?

1
  • try the click binding
    – CodeThug
    May 7, 2013 at 20:13

2 Answers 2

12

If you just change

valueUpdate: 'afterkeydown'

to

valueUpdate: 'input'

it hooks that event to trigger the value update. It's better overall because it also handles clipboard-based actions and text drag-drop actions.

3
  • Nice find! This worked for me too. I'm changing to yours as the answer and updating my Fiddle.
    – AlignedDev
    Jun 26, 2013 at 19:07
  • Yes perfect solution. Dec 12, 2017 at 13:07
  • I found that changing the data-bind from value to textInput resolved the issue nicely. In order to stop it updating after every key I made it a rate limiting observable: knockoutjs.com/documentation/rateLimit-observable.html for details. Dec 12, 2017 at 14:37
5

I figured it out using the input event and Knockout's event binding. Here is my JsFiddle showing the solution with the code below.

<input type="search" id="input1" data-bind="value: textForBox, valueUpdate: 'afterkeydown',
  event: { input: cleared }" />
var vm = {
    textForBox: ko.observable(),
    cleared: function (data, event) {
        if (event.currentTarget.value === '') {
           this.textForBox('');
        }
    }
};
ko.applyBindings(vm);

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.