Mina Matta Mina Matta - 17 days ago 12
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

textbox


<!DOCTYPE html>
<html>
<head>
<title>Knockout</title>
<meta charset="utf-8" />
</head>
<body>
<div id="view">
<input type="text" placeholder="Press enter to bind" data-bind="value:textboxValue" data-function="pressEnterToBind"/>
</div>
</body>
</html>
<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>
<script>
$(document).ready(function () {
window.vm = (function ($, ko) {
var $view = $("#view");
var textboxValue = ko.observable();

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

init();

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

window.vm.binding = (function (ko, vm) {
ko.applyBindings(vm);
})(ko, window.vm);
});
</script>


Results for alert is 'undefined'

Answer

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"/>  

OR

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

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