Mina Matta Mina Matta - 10 months ago 67
jQuery Question

Knockout keypress does not bind when press enter

I am trying to enable search functionality when user press enter using knockout
but when I press enter in textbox, knockout doesn't bind the value from


<!DOCTYPE html>
<meta charset="utf-8" />
<div id="view">
<input type="text" placeholder="Press enter to bind" data-bind="value:textboxValue" data-function="pressEnterToBind"/>
<script src="https://code.jquery.com/jquery-3.1.1.min.js"></script>
<script src="http://knockoutjs.com/downloads/knockout-3.4.1.js"></script>
$(document).ready(function () {
window.vm = (function ($, ko) {
var $view = $("#view");
var textboxValue = ko.observable();

var onPressEnter = function (e) {
if (e.which === 13) {
init = function () {
$view.on('keypress', '[data-function="pressEnterToBind"]', onPressEnter);


return {
textboxValue: textboxValue
}($, ko));

window.vm.binding = (function (ko, vm) {
})(ko, window.vm);

Results for alert is 'undefined'

Answer Source

I reached my goal by two ways

First: adding "valueUpdate: 'afterkeydown'" to knockout binding

<input type="text" placeholder="Press enter to bind" data-bind="value:textboxValue,valueUpdate: 'afterkeydown'"  data-function="pressEnterToBind"/>  


Second: "blur()" and "focus()" again on target control

            var onPressEnter = function (e) {
                if (e.which === 13) {
                    $(e.target).blur(); // to refresh ko binding
                    $(e.target).focus(); // to refresh ko binding