0

I'm creating a chat application with node.js and I'm setting a variable called message to equal $('#posttext'), then I try to call message.val() and get undefined. I do the same with variable output and attempting to output.append() doesn't do anything.

My JS:

var socket = io.connect('http://localhost:4000');

// Going Through DOM
var message = $('#posttext');
var output = $('#chat-row');

// Control Length Of Text & Emit Events
var maxchars = 120;

$(function(){
  $('#posttext').keyup(function(e) {
    if (e.keyCode == 13) {
      socket.emit('chat', {
        message: message.val(),
        handle: 'Dev',
        userType: 'Mod',
        avatar: 'https://steamcdn-a.akamaihd.net/steamcommunity/public/images/avatars/43/43bdf487f1f69fe7459ca354ea9b54dbc313849e.jpg'
      });
    }
    var tlength = $(this).val().length;
    $(this).val($(this).val().substring(0, maxchars));
    var tlength = $(this).val().length;
  });
});


// Listen for Events
socket.on('chat', function(data){
  output.append('<img src="' + data.avatar + '" alt="Chat Avatar" class="ChatAvatar"> <div class="' + data.userType + 'ChatName">' + data.handle + '</div> <div class="' + data.userType + 'ChatMsg">' + data.message + '</div>');
});

My HTML:

<div id="Chat">
 <div id="chat-wrap">
  <div id="chat-box">
   <button id="chatScrollButton" onclick="scrollDownChat()">More Messages Below</button>
   <div id="chat-row"></div>
  </div>
  <form id="send-message-area">
   <textarea id="posttext" placeholder="Say Something (English)" maxlength="120"></textarea>
  </form>
 </div>
</div>

It works when I change message to $('#posttext'), yet it doesn't work with the variable why? And how can I fix it?

Also sorry about the trashy HTML indenting, the code lost format when I pasted it into here.

Tim Rumit
  • 45
  • 2
  • 10

0 Answers0