How to listen to the form submit event in the meteorjs template?

If I have a template like this

<template name="my_form">
  <form name="my_form">
    <input name=" ....
  </form>
</template>

I would like to listen to the send event "my_form".

I tried this:

Template.my_form.events({
  'submit form': function( event ){   // also tried just 'submit'
    console.log( 'Submitting form!' );
    event.preventDefault();
    event.stopPropagation();
    return false; 
  }
});

But no luck. It looks like the event handler is not being logged. Is something missing?

ps I know that I can handle the "view" form by listening to the submit button click event, but I need to use the form submit event in this particular scenario.

+4
source share
3 answers

It doesn't look like you're missing something. I could not reproduce your problem. When a hit is returned while the textinput object is in focus, the console prints "Submit form!" as was expected.

, :

form.html:

<head>
  <title>form</title>
</head>

<body>
  {{> my_form}}
</body>

<template name="my_form">
  <form name="my_form">
    <input></input>
  </form>
</template>

form.js

if (Meteor.isClient) {
    Template.my_form.events({
      'submit form': function( event ){   // also tried just 'submit', both work for me!
        console.log( 'Submitting form!' );
        event.preventDefault();
        event.stopPropagation();
        return false; 
      }
    });
}
+7

.

$("my_form").submit(function (e) {
      e.preventDefault();
});
+2

You can create one event of the submit form, and you conditionally check the target field of the event. Call the appropriate Meteor method based on the collection you are inserting into.

Template.detailsViewTemplate.events({
    'submit form': function(ev){
        ev.preventDefault();

        var detail_input_field = template.$('#detail_entry');
        var message_input_field = template.$('#message_entry');

        if(detail_input_field != undefined){
            var detailFormData = {
            detail: $(ev.target).find('[name = detail]').val(),
            parentId: $(ev.target).find('[name = parentId]').val(),
            checkboxStatus: ''
            }

            Meteor.call('addDetail', detailFormData);
            $('.form-group').children().val('');

        } else if(message_input_field != undefined){
            var newMessageData = {
                listId: this.params_id,
                message: $(ev.target).find('[name = message]').val()
            }
            Meteor.call('addMessage', newMessageData);
            $('.form-group').children().val('');
        }
    }
}
+1
source

All Articles