Reputation: 155
i'm trying to save data on mongodb with a form on meteor and ti should work but it doesn't i'm totally lost i'm running meteor 0.7.0.1 on a windows 7 machine
bookshell.html
<body>
{{> addBook}}
{{> bookshell}}
</body>
<template name="bookshell">
<ul>
{{#each books}}
<li>{{subject}}</li>
{{/each}}
</ul>
</template>
<template name="addBook">
<form class="addBookForm">
<input type="text" class="subject" placeholder="Subject">
<button type="submit" class="btn btn-primary">add book</button>
</form>
</template>
bookshell.js
books = new Meteor.Collection("books");
if (Meteor.isClient) {
Template.addBook.events({
'.submit .addBookForm' : function (e) {
e.preventDefault();
books.insert({
subject: $(".subject").val(),
});
}
});
Template.bookshell.books = function () {
return books.find({}, {sort: {subject: 1}});
};
}
someone knows why it doesn't work?
Upvotes: 1
Views: 3310
Reputation: 7680
Just change:
'.submit .addBookForm'
to:
'submit .addBookForm'
Also, you might want to scope your ".subject"
selector to the template instance:
Template.addBook.events({
'submit .addBookForm' : function (event, template) {
event.preventDefault();
books.insert({
subject: template.find(".subject").value,
});
}
});
Upvotes: 0
Reputation: 64342
Templates have a submit
event, and the handler will isolate the submit to the template. So unless you have more than one form on the template you can just do this:
Template.addBook.events({
submit: function () {
books.insert({subject: $(".subject").val()});
return false;
}
});
Note from the docs:
Returning false from a handler is the same as calling both stopImmediatePropagation and preventDefault on the event.
Upvotes: 4
Reputation: 21384
I don't think there are Template events on form submission. Just put the event on the button (and perhaps even remove the form, or prevent the default):
Give your button and id:
<button id="submitbutton" class="btn btn-primary">add book</button>
And add a click event to it:
Template.addBook.events({
'click #submitbutton' : function (e) {
e.preventDefault();
books.insert({
subject: $(".subject").val(),
});
}
});
Upvotes: 0