Is there any way to avoid knockoutjs submit binding submit form when I press enter?

According to the documentation (knockoutjs.com/documentation/submit-binding.html) the knockoutjs submit binding has the advantage that it captures alternative forms submission methods, such as pressing the enter key while entering text into a text box, I have a grid in my form, and some users try to use an input key to move from one field to another. Is there a way to avoid submitting the form when this happens?

+5
source share
1 answer

One option is to add a handler keypressto the form, which absorbs the input key. It will look like this:

<form data-bind="event: { keypress: absorbEnter }, submit: test">
    <div data-bind="absorbEnter: true">
    <input data-bind="value: name">
    <input type="submit" value="Go" />
    </div>
</form>

JS:

var viewModel = {
    name: ko.observable("test"),
    absorbEnter: function(data, event) {
       return event.keyCode !== 13;  
    },
    test: function() {
        console.log("submitting", arguments);        
    }
};
ko.applyBindings(viewModel);

: http://jsfiddle.net/rniemeyer/FvZXj/2/

+8

All Articles