Prevent Form Submission when Pressing Enter Key in Meteor Templates

Form layout is nice and if you are using Meteor Templates with forms to collect some data just for internal processing, then the chances are your forms may be come with unwanted submit behaviors for Enter key presses.

For example, consider this below template:

<template name="InputForm">    
    <form id="URIForm" class="form-horizontal">
        <div class="form-group">
            <label class="col-md-2 control-label" for="esURI">URL</label>
            <div class="col-md-6">
                <div class="input-group">
                <input id="URI" name="URI" class="form-control" type="url" required>
                <a href="#" class="input-group-addon btn btn-primary"><span class="glyphicon glyphicon-cloud-download"></span> Load</a>
                </div>
            </div>
        </div>
    </form>
</template>

When user enters any text into the input text field and presses Enter key, you can see the whole page getting refreshed for Meteor, which may no tbe what you want.

To prevent this behavior, you can use the below code in the template render event.

Template['InputForm'].rendered = function () {
    this.$("form").on("submit", function (e) { e.preventDefault() });
}

The e.preventDefault() takes care of preventing the default form submission action, so that you can handle the button click events explicitly.

Also, by using this code in the template rendered method with this.$('form'), all forms inside the current template get affected by the override, and any other forms in other templates will behave as usual. Instead, to do a global form behavior override that is applicable for all forms no matter where they are, use instead $('form') without this.

And if your template have multiple forms and you want to prevent the default behavior for only particular or specific forms, then you can select them by their idtagname, such as this.$("#URIForm")

Comments