Nicholas Hendricks Nicholas Hendricks - 1 month ago 10
HTML Question

printing a variable into a div

so i am atempting to build a chatroom with node.js and socket.io and i have gotten so far as to get the users input and send it to the node server but thats all i want to be able to display it up in a div here is my client side script

var socket = io();

$('form').submit(function(e) {
e.preventDefault();

//gets the value from the message text feild and sets it as the message var
var message = {
text : $('#chat-box-div-txtinpt').val()
}
if (message.text.trim().length !== 0) {
socket.emit('chat-message', message);
}
$('#chat-box-div-txtinpt').focus();
document.getElementById('chat-box-div-txtinpt').value='';
});


and here is my server script

var app = require('express')();
var http = require('http').Server(app);
var io = require('socket.io')(http);

app.get('/', function(req, res){
res.sendfile('index.html');
});
http.listen(3000, function(){
console.log('listening on *:3000');
});
io.on('connection', function (socket) {

console.log('a user connected');
socket.on('disconnect', function () {
console.log('user disconected');
});

socket.on('chat-message', function (message) {
console.log('message : ' + message.text);
});
});


here is the site

KFE KFE
Answer

It appears you're using jQuery, so for this line: document.getElementById('chat-box-div-txtinpt').value=''; you could just do $('#chat-box-div-txtinpt').val('');

to answer your question: you could just do $('#chatlog-display-div').append(message.text)

Your code would end up looking something like this

 $('form').submit(function(e) {
    e.preventDefault();

        //gets the value from the message text feild and sets it as the message var
    var message = {
        text : $('#chat-box-div-txtinpt').val()
    }
    if (message.text.trim().length !== 0) {
      socket.emit('chat-message', message);

      //append the message to the chatlog-display-div
      $('#chatlog-display-div').append(message.text);
    }
    //clear the value of the txtinput after you focus it.
    $('#chat-box-div-txtinpt').focus().val('');
});

please mark as accepted answer if you feel this adequately solves the issue.