Gayathri
May 2, 2021

Chatbot using Javascript

simple chatbot code using javascript:
Here is my chatbot.html:

<html>
<head>
<script type=”text/javascript” src=”chatbot.js”></script>
<link rel=”stylesheet” href=”style.css”></head>
<body>
<div class=”scroll centered”>
<p id=”textarea”></p>
</div>
<div class=”userFields”><input id=”msg” type=”text” placeholder=”type something…”><button onclick=”replyToChat()”>send</button></div></body>
</html>
In this I just use “input” field and “button”. After clicking the button the replyToChat function will be called to get a response.

Here is my Js file:

var words={
“hi”:”Hello”,
“how are you”:”Fine! and you?”
};

function replyToChat()
{
var userMessage=document.getElementById(“msg”).value.toLowerCase();
document.getElementById(“textarea”).innerHTML += “You:”+userMessage +”<br>”;
if(userMessage in words){
document.getElementById(“textarea”).innerHTML += “Bot:”+words[userMessage] +”<br>”;
}
else{
document.getElementById(“textarea”).innerHTML += “Bot:”+”I don’t understand <br>”;
}
document.getElementById(“msg”).value=””;
}
In replyToChat function I just use the “getElementById” to get the user typed value and used the object for reply. You can add your own data in words.

Sample chatbot

Hope you understand! I’ll post next version of chatbot soon..