2
votes

I'm using Knockout.js to build most of my UI and I'm looking for a tidy way to select the text in any input[type=text] on focus. In the past I've done things like:

$('input[type=text]').click(function() { $(this).select(); });

But under the Knockout paradigm, new inputs are being created and removed all the time in response to my view model changes. I don't want to have to do too much procedural stuff to re-bind handlers to new elements, I don't want to add a click binding to every single input instance in my templates, and I don't really want to use jQuery's live to watch the whole document due to the performance and other drawbacks.

These inputs can appear at all levels throughout my template hierarchy. Is there a clean way to hook into any new DOM structures having been built by Knockout in response to my view model changes and wire up child inputs transparently?

1
Why not binding a KO click handler? data-bind="click: selectText, value: text". You could even write an extender for this.thomaux
Yeah, it's just that I'll have a lot of inputs and don't really want to add this individually, but maybe it's not so bad.Tom W Hall
You could also write your own binder that does this for you, take a look at the doc on how to do this, you can extend value binder and add the focus part yourself, it should do the trick. You'd need to replace all your current value bindings however. Not sure if you could overwrite the value binding.thomaux
Yep. I upvoted your comment because you convinced me that a straight binding to a selectText function on the appropriate inputs is the best way. I'm doing this for simple text inputs like a first name, and for more complex cases where for example a currency value has to be formatted differently upon focus, I'm using Knockout binding handlers. Cheers.Tom W Hall
Allright, glad to help! I've added to comment as answer, could you accept so this question is no longer unanswered? Cheers!thomaux

1 Answers

0
votes

You could write your own custom binder that does this for you, take a look at the doc on how to do this. You can extend the value: binding and add the focus part yourself, it should do the trick. You'd need to replace all current value bindings with your custom one, where needed.