Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

If I have a template like this

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

I'd like to listen to the submit event of "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 appears the event handler doesn't get registered. Is there something I'm missing?

p.s. I am aware that I can handle a form "submission" by listening to the submit button click event, but I need to use the form submit event in this specific scenario.

like image 771
0x6A75616E Avatar asked Dec 12 '13 07:12

0x6A75616E


3 Answers

Doesn't seem like you are missing something. I was not able to reproduce your problem. When hitting return while the textinput has focus the console prints 'Submitting form!' as expected.

My code, just two files:

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; 
      }
    });
}
like image 123
Tobias Avatar answered Oct 02 '22 01:10

Tobias


You can use general listener for it.

$("my_form").submit(function (e) {
      e.preventDefault();
});
like image 35
Ahmet Uğur Avatar answered Oct 02 '22 02:10

Ahmet Uğur


You can create a single submit form event, and you conditionally check the event target field. Call 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('');
        }
    }
}
like image 20
redress Avatar answered Oct 02 '22 03:10

redress