I am listening for selectionStart
and selectionEnd
with knockout and it’s working fine when the user clicks with the mouse and drags rightward to create the selection. But if the user clicks in the text and drags the mouse leftwards to create the selection, the proper values are not being returned: selectionEnd and selectionStart are in that case the same value, e.g. 6 and 6 when I select a six-letter word moving right-to-left with the mouse.
Here’s my binding:
<input type="text" data-bind="textInput: Model.searchWord, event:{keyup: Model.saveSelection, mouseup: Model.saveSelection, mousedown: Model.saveSelection, click: Model.saveSelection}" />
P.S. I’ve also tried without listening for the click event.
and here’s the code:
self.selectionStart = ko.observable();
self.selectionEnd = ko.observable();
self.saveSelection = function (v1, keyEvent) {
self.selectionStart(keyEvent.target.selectionStart);
if (keyEvent.target.selectionEnd) {
self.selectionEnd(keyEvent.target.selectionEnd);
} else {
self.selectionEnd(0);
}
if (keyEvent.type == "mousedown") return true;
if (keyEvent.type == "mouseup") return true;
}
2
Answers
In my case I'm working with a home-grown virtual keyboard that injects characters not found on the user's keyboard into the observable backing the Input element. Sometimes it will be an appended or inserted character, and sometimes it will replace a selection. So the selection start and end values have to be captured in the
blur
event as well.There is an error in your JavaScript example:
You’re assigning to keyEvent.type instead of doing a comparison. Try:
I have a working example that shows selection correctly at: https://playcode.io/1351651