0

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 2

0

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.

Sign up to request clarification or add additional context in comments.

Comments

0

There is an error in your JavaScript example:

 if (keyEvent.type = "mousedown") return true;
 if (keyEvent.type = "mouseup") return true; 

You're assigning to keyEvent.type instead of doing a comparison. Try:

 if (keyEvent.type === "mousedown") return true;
 if (keyEvent.type === "mouseup") return true; 

I have a working example that shows selection correctly at: https://playcode.io/1351651

2 Comments

Ah, thanks for pointing that out. Typo crept in here on SO when I was editing the question, not in the original code.
I needed to get the selectionStart and selectionEnd for the input when I clicked on a virtual keyboard to add a character not available on the physical one; unless I saved those values in the blur event, it wasn't working properly at that juncture.

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.