phoenixCoder phoenixCoder - 7 months ago 120
Javascript Question

HTML5 jQuery Chat box interface with hardcoded response

I'm finishing up my project and am just trying to get a simulated server response or at least echoed response from the user input. The whole idea is that both messages should show up in the chat box area. Right now the hardcoded is not displaying. Here is my javascript/jQuery:

<script>
$(document).ready(function(){
$('#submitmsg')
.bind('click', function(){
var message = $('#usermsg').val();
$('#chatbox').append('<p>' + message + '</p>');
$('#usermsg').val('');
});
.bind('click', function(){
var message = $('#usermsg').val();
$('#chatbox').append('<p>' + message + '</p>');
$('#usermsg').val('');
});
</script>


here is some my html:

<body>
<div id="wrapper">
<div id="menu">
<p class="welcome">Welcome</p>
<p class="logout"><a id="exit" href="window.top.close();">Exit Chat</a></p>
<div style="clear:both"></div>
</div>

<div id="chatbox">
<p>Here's our chat data</p>
</div>

<form name="message">
<input name="usermsg" type="text" id="usermsg" size="63" />
<button type="button" id="submitmsg" value="send">Send</button>
</form>


I am attempting to use the .bind method in order to tie the initial message as well as the coded response to the event so that the messages will be output simultaneously into the chat box but it is not doing such.

Answer

How about something like this?

jsfiddle Demo

$(document).ready(function() {
  $('#submitmsg')
    .bind('click', function() {
      var message = $('#usermsg').val();
      $('#chatbox').append('<p>' + message + '</p>');
      $('#usermsg').val('');
      serverResponse(message);
    });
});

function serverResponse(message) {
  $('#chatbox').append('<p>Server: ' + message + '</p>');
}
<div id="menu">
  <p class="welcome">Welcome</p>
  <p class="logout"><a id="exit" href="window.top.close();">Exit Chat</a></p>
  <div style="clear:both"></div>
</div>
<div id="chatbox">
  <p>Here's our chat data</p>
</div>
<form name="message">
  <input name="usermsg" type="text" id="usermsg" size="63" />
  <button type="button" id="submitmsg" value="send">Send</button>
</form>

Comments