简体   繁体   中英

Submit comment by pressing enter?

I am making a chat app with Meteor using this tutorial ( http://code.tutsplus.com/tutorials/real-time-messaging-for-meteor-with-meteor-streams--net-33409 ) and I am stuck at trying to make it where if you press enter it submits your comment instead of having to press the Send button everytime.

Below is the javascript code the app uses to submit a comment by pressing the Send button, but does anyone know what code I need to put in to be able to submit a comment by pressing enter?

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

I would recommend you to place your form in a <form> -element, and get this functionality for free if you use an <input> -element instead of a <textarea> -element (if I wrote text in a <textarea> -element that submitted the form when I pressed enter I would go crazy!). Just listen for the forms submit event.

You need to capture the keypress event and take the same action therein:

 function sendMessage() {
   var message = $('#chat-message').val();
    chatCollection.insert({
     userId: 'me',
     message: message
   });
   $('#chat-message').val('');

   //add the message to the stream
   chatStream.emit('chat', message);
  }

  Template.chatBox.events({
      // Capture the `keyup` event on the `input` element.
      "keyup input": function(ev) {
        if(ev.which === 13) {  // If it was an enter key
          sendMessage();
        }
      },
      "click #send": function () { sendMessage(); }
    });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM