The problem is that you overwrite the current HTML of #container
by calling $().html
instead of $().append
. You should call $().append
to add values to the current HTML of the container without overwriting it. You should also add <br>
after each attempt to change the HTML of the container to separate the messages by a new line.
Here's your JSFiddle: http://jsfiddle.net/3wySt/10/
Javascript
var username = "";
function send_message(message){
$("#container").append("<span class=&bot&><b>Chatbot:</b> </span>" + message + "<br>"); //Notice the .append instead of .html and the <br>
}
function get_username(){
send_message("Hello, what is your name?");
}
function ai(message){
if (username.length < 3){
username = message;
send_message("Nice to meet you " + username + ", how are you doing?");
}
}
$(function(){
get_username();
$("#textbox").keypress(function(event){
if ( event.which == 13){
if ( $("#enter").prop("checked") ){
$("#send").click();
event.preventDefault();
}
}
});
$("#send").click(function(){
var username = "<span class="username">You: </span>";
var newMessage = $("#textbox").val();
$("#textbox").val("");
var prevState = $("#container").html();
if (prevState.length > 3){
prevState = prevState + "";
}
$("#container").html(prevState + username + newMessage + "<br>"); //Notice the <br>
$("#container").scrollTop($("#container").prop("scrollHeight"));
ai(newMessage);
});
});