Submit message by pressing enter?

核能气质少年 提交于 2019-12-24 03:36:08

问题


I am working on a chat app built with Meteor based off of this tutorial (http://code.tutsplus.com/tutorials/real-time-messaging-for-meteor-with-meteor-streams--net-33409) and I am trying to make it where if you press enter it submits your message instead of having to press the Send button.

Below is the javascript code the app uses to submit a comment by pressing the Send button, but does anyone know how to add the enter feature?

// when Send Chat clicked add the message to the collection
Template.chatBox.events({
  "click #send": function() {
    var message = $('#chat-message').val();
    chatCollection.insert({
     userId: 'me',
     message: message
   });
   $('#chat-message').val('');

   //add the message to the stream
   chatStream.emit('chat', message);
  }
});
chatStream.on('chat', function(message) {
  chatCollection.insert({
    userId: this.userId,
    subscriptionId: this.subscriptionId,
    message: message
  });
});

回答1:


You need to check for a key press event. You can find a full list of the codes for each key here: http://www.cambiaresearch.com/articles/15/javascript-char-codes-key-codes

Best way to do this would be make the function in the click event a named function and then you can just run the same function on both events.

Template.chatBox.events({
 "click #send": function() {
    var message = $('#chat-message').val();
    chatCollection.insert({
      userId: 'me',
      message: message
    });
    $('#chat-message').val('');

    //add the message to the stream
    chatStream.emit('chat', message);
  },
  "keypress #chat-message": function(e) { 
    if (e.which == 13) {
      console.log("you pressed enter");
      //repeat function from #send click event here
     }
  }
});



回答2:


'keypress #send': function (evt) {
     if (evt.which === 13) {

13 is the keycode for enter. If you want to change it you can look up the javascript keycodes so you can bind to whatever you like.

You might want to consider familiarizing yourself with the api http://docs.meteor.com/



来源:https://stackoverflow.com/questions/21897058/submit-message-by-pressing-enter

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!