Can i use 'oninput' in a knockout binding?

821 views
Skip to first unread message

jk

unread,
Jun 5, 2015, 8:36:30 PM6/5/15
to knock...@googlegroups.com
I thought after reading the opening paragraph of http://knockoutjs.com/documentation/event-binding.html that knockout only binds events to  keypressmouseover or mouseout.
But the same para says about event binding that "This can be used to bind to any event".
I am just unable to make an 'oninput' event happen.

In my code I would like to process each character immediately as it is typed by the user in the search box by 
linking 'oninput' event to a function. 

My code is:

<!DOCTYPE html> <html> <head> <script type="text/javascript" src="jquery-2.1.3.min.js"></script> <script type="text/javascript" src="knockout-3.3.0.js"></script> <style type="text/css"> ul { border: 1px solid black; list-style-type: none; } </style> </head> <body> <ul data-bind="foreach: { data: location }"> <li data-bind="text: $data.item, visible: $data.show"></li> </ul> <p>Search: <input id="myInput" data-bind=" event: {oninput: myFunction}, textInput: userName" /></p> <p id="demo"></p> <script type="text/javascript"> ko.applyBindings({ location: ko.observableArray([ { item:'Apples', show: false, }, { item:'Carrots', show: true, } }]), userName: "Harry", showListItem: true, myFunction: function() { var x = document.getElementById("myInput").value; document.getElementById("demo").innerHTML = "You wrote: " + x; return true; } }); </script> </body> </html>

Ian Yates

unread,
Jun 6, 2015, 2:42:11 AM6/6/15
to knock...@googlegroups.com

jk

unread,
Jun 6, 2015, 11:46:03 PM6/6/15
to knock...@googlegroups.com
Using textInput binding, how could I have myFunction called and executed? 

Ian Yates

unread,
Jun 7, 2015, 12:36:19 AM6/7/15
to knock...@googlegroups.com
make userName observable, and then subscribe to it. 
The code of 'myFunction' could also be handled by having a data-bind in your HTML for something like a span element.

jk

unread,
Jun 7, 2015, 3:24:00 AM6/7/15
to knock...@googlegroups.com
superb! I needed the subscribe function. Thanks much!
Reply all
Reply to author
Forward
0 new messages