I would like to have a form in my Meteor html template and on submit insert that data to my MongoDB list. My questions are:
JQuery is included in meteor & very simplifying, why would you want to avoid it? Its quite long to traverse the dom manually with js
You could use javascript to submit your forms ajax style:
So you could just use normal form html in your template like usual:
// HTML
<form id="myform">
<input type="text" name="firstname"/>
<input type="text" name="lastname"/>
<input type="text" name="email"/>
<input type="submit" id="submit"/>
</form>
// Client JS
function submitme() {
form = {};
$.each($('#myform').serializeArray(), function() {
form[this.name] = this.value;
});
// Do validation on
// form = {
// firstname: 'first name',
// lastname: 'last name',
// email: '[email protected]'
// }
MyCollection.insert(form, function(err) {
if(!err) {
alert("Submitted!");
$('#myform')[0].reset();
} else {
alert("Something is wrong");
console.log(err);
}
});
}
You could bind the select button to insert the data when clicked:
Event map binding:
Template.templatename.events({
'submit' : function(event) {
event.preventDefault(); //prevent page refresh
submitme();
}
});
If you HATE jQuery & cant use it at all
// HTML
<form id="myform">
<input id="firstname" type="text" name="firstname"/>
<input id="lastname" type="text" name="lastname"/>
<input id="email" type="text" name="email"/>
<input type="submit" id="submit"/>
</form>
// Client JS
function submitme() {
form = {
firstname: firstname.value,
lastname: lastname.value,
email: email.value
};
// Do validation on
// form = {
// firstname: 'first name',
// lastname: 'last name',
// email: '[email protected]'
// }
MyCollection.insert(form, function(err) {
if (!err) {
alert("Submitted!");
// Empty field values
email.value = "";
firstname.value = "";
lastname.value = "";
} else {
alert("Something is wrong");
console.log(err);
}
});
}