Submitting a form in Meteor without using extras

George Katsanos picture George Katsanos · Mar 4, 2013 · Viewed 13.8k times · Source

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:

  • Is this possible without using extra packages? Could I just add an HTML form as a template?
  • Does the on submit event work for latest Meteor?
  • I've read that we can use the click event for the submit button: Could you tell me how I would go for finding in my DOM the values of my input elements? (without using jQuery?)

Answer

Akshat picture Akshat · Mar 4, 2013

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);
        }
    });
}