Search code examples
javascriptjquerymeteoruser-accounts

Meteor user adding form doesn't do anything?


So I made my own user adding form so that only logged in users can add new ones. Here's my Jade:

template(name="userAdd")
.sixteen.wide.column
  h1 Add new user
  form#userAddForm.ui.form
    .field.required
      label(for="username") Username:
      input(type="text" name="username")#username
    .field.required
      label(for="email") Email:
      input(type="email" name="email")#email
    .field.required
      label(for="password") Password:
      input(type="password" name="password")#password
    .field.required
      label(for="realname") Real Name:
      input(type="text" name="realname")#realname
    .field.required
      label(for="bio") Bio:
      textarea(rows="3" name="bio")#bio
    button(type="submit")#usersubmit.ui.button.primary Submit

And the Javascript:

Template.userAdd.events({
  'click #usersubmit': function (evt) {
    Accounts.createUser({
      username: $('input #username').val(),
      email: $('input #email').val(),
      password: $('input #password').val(),
      profile: {
        realname: $('input #realname').val(),
        bio: $('input #bio').val()
      }
    })

    Router.go('/')
  }
})

For some reason, this only redirects me back to the same page and doesn't do anything, not even something shows in the dev console. What am I doing wrong?


Solution

  • Because it is actually submitting the form. You need to stop the form from submitting. Use the following code.

    Template.userAdd.events({
        'submit form': function(event){
            event.preventDefault();
    
            Accounts.createUser({
                username: event.target.username.value,
                email: event.target.email.value,
                password: event.target.password.value,
                profile: {
                    realname: event.target.realname.value,
                    bio: event.target.bio.value
                }
            });
    
            Router.go('/');
        }
    });
    

    Notice that I use event.target.inputName.value which is the best practice way of dealing with form data in Meteor.