Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to avoid that the submit binding of knockoutjs sends the form when pressing the enter key?

Tags:

knockout.js

According to the documentation (knockoutjs.com/documentation/submit-binding.html) the submit binding of knockoutjs has the advantage that it captures alternative ways to submit the form, such as pressing the enter key while typing into a text box. I have a grid on my form and some users are trying to use the enter key to go from one field to the next. Is there a way to avoid submitting the form when this happens?

like image 300
jgarza Avatar asked Apr 23 '12 17:04

jgarza


People also ask

How do I stop form submission on Enter key?

To prevent form submission when the Enter key is pressed in React, use the preventDefault() method on the event object, e.g. event. preventDefault() . The preventDefault method prevents the browser from refreshing the page when the form is submitted.

How do you prevent form submit on Enter in JavaScript?

What ever the reason, if you want to prevent the form submission on pressing Enter key, you can write the following function in javascript: $(document). ready(function() { $(window). keydown(function(event){ if(event.

Should hitting enter submit a form?

Generally - yes, it is best practice to allow the user to hit enter to submit the form at any time.

How do I submit a form to the enter press?

To submit the form using 'Enter' button, we will use jQuery keypress() method and to check the 'Enter' button is pressed or not, we will use 'Enter' button key code value.


1 Answers

One choice is to add a keypress handler on the form as well that absorbs the enter key. It would look like:

<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);

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

like image 124
RP Niemeyer Avatar answered Sep 28 '22 08:09

RP Niemeyer