Lucas Veiga
Lucas Veiga

Reputation: 197

Two identical keydown events; only one works

I'm trying to build an webapp using Meter. I have this in client.js:

Template.messages.helpers({
    messages: function() {
        return Messages.find({}, { sort: { time: -1}});
    }

})

Template.chats.helpers({
    chats: function() {
        return Chats.find({}, { sort: { time: -1}});
    }

})

Template.input.events({
    "keydown input#message" : function (event) {
      if (event.which == 13) { // 13 is the enter key event
        if (Meteor.user())
          var name = Meteor.user().username;
        else
          var name = 'Anonymous';
        var message = document.getElementById('message');

        if (message.value != '') {
          Messages.insert({
            name: name,
            message: message.value,
            time: Date.now(),
          });

          document.getElementById('message').value = '';
          message.value = '';
        }
      }
    }
});

Template.inputchat.events({
    "keydown inputchat#chatid" : function (event) {
        if (event.which == 13) { // 13 is the enter key event
          if (Meteor.user())
            var name = Meteor.user().username;
          else
            var name = 'Anonymous';
          var chat = document.getElementById('chatid');

          if (chat.value != '') {
            Chats.insert({
              name: name,
              title: chat.value,
              time: Date.now(),
            });

            document.getElementById('chatid').value = '';
            chat.value = '';
          }
        }
    }
});

And in my html file:

<template name="Index">
<body>
  {{> input }}
  {{> messages }}
  {{> inputchat }}
  {{> chats }}
</body>
</template>
<template name="input">
  <p>Message: <input type="text" id="message"></p>
</template>

<template name="inputchat">
  <p>Chat name: <input type="text" id="chatid"></p>
</template>

<template name="messages">
  {{#each messages}}
    <strong>{{name}}:</strong> {{message}}<br>
  {{/each}}
</template>

<template name="chats">
  {{#each chats}}
    <strong>{{name}}:</strong> {{chat}}<br>
  {{/each}}
</template>

Finally, this in models.js:

Messages = new Mongo.Collection('messages');
Chats = new Mongo.Collection('chats');

When I type something and hit enter on {{> input }}, everything works fine. The message is added to the collection and template and the input box becomes empty.

I was looking for the same thing when typing and hitting enter on inputchat. However, nothing happens. Thanks.

Upvotes: 1

Views: 108

Answers (1)

Ethaan
Ethaan

Reputation: 11376

Try with First Solution

 Template.input.events({
        "keydown #message" : function (event) {
       }
     })

Use IDS

Second Solution

also replace "keydown inpuchat" to just "keydown input#chatid

Upvotes: 1

Related Questions