Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Handle IE 9 & 10's clear button with Knockout binding

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?

like image 534
AlignedDev Avatar asked May 07 '13 14:05

AlignedDev


2 Answers

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.

like image 186
Hafthor Avatar answered Sep 21 '22 14:09

Hafthor


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);
like image 44
AlignedDev Avatar answered Sep 24 '22 14:09

AlignedDev