Search code examples
javascriptjquerymeteormeteor-blaze

Cannot get the input value using click event in meteorjs


I am new to meteor and am having some problem in click event.

The code is:

Template.addPost.events({
 'click button':function(event){
    event.preventDefault();
    var postName=event.target.postName.value;
    Posts.insert({
      name:postName,
      createdAt:new Date()
    });
    event.target.postName.value='';
  }
});

HTML code is:

<template name='addPost'>
  <input type='text' placeholder='Add post here' name='postName'>
  <button class="btn btn" type="button">Post</button>
</template>

However in the browser on clicking the button the input value is not inserted to the mongo database.


Solution

  • The click event is on the button but you want to refer to the value of the input field in your insert. You already have a name for your input field so you can refer to it using jQuery and a name selector:

    Template.addPost.events({
     'click button': function(event){
        event.preventDefault();
        var postName = $('input[name="postName"]').val();
        Posts.insert({ name: postName, createdAt: new Date() });
        $('input[name="postName"]').val('');
      }
    });