<!DOCTYPE html> <html> <head> <title>Chatbot Demo</title> </head> <body> <h1>Chatbot…
- User
<script> // Define the knowledge base for case-based reasoning var knowledgeBase = { “hello”: “Hi, how can I help you?”, “name”: “My name is Chatbot!”, “how are you?”: “I’m good, thank you!”, “default”: “I’m sorry, I couldn’t understand. Can you please rephrase?” }; // Function to send a message function sendMessage() { var userInput = document.getElementById(“userinput”).value; var response = getResponse(userInput); displayMessage(userInput, “user”); displayMessage(response, “bot”); document.getElementById(“userinput”).value = “”; } // Function to get the bot’s response based on user input function getResponse(input) { // Convert input to lowercase for case-insensitive matching var key = input.toLowerCase(); // Check if input matches with any key in the knowledge base if (knowledgeBase.hasOwnProperty(key)) { return knowledgeBase[key]; } // If no exact match, return the default response return knowledgeBase[“default”]; } // Function to display the message in the chatlog function displayMessage(message, sender) { var chatlog = document.getElementById(“chatlog”); // Create a new message element with a class based on the sender var messageElement = document.createElement(“div”); messageElement.classList.add(sender); // Set the text of the message element messageElement.textContent = message; // Append the message element to the chatlog chatlog.appendChild(messageElement); } </script> - Assistant
This is a simple chatbot demo in HTML.
The chatbot uses a knowledge base, which is an object that maps user inputs to bot responses. The knowledge base is defined at the beginning of the script.
The
sendMessage()function is called when the user clicks the "Send" button. It retrieves the user input from the text input field, gets the bot's response using thegetResponse()function, displays the user message in the chatlog using thedisplayMessage()function, displays the bot's response in the chatlog using thedisplayMessage()function, and clears the input field.The
getResponse()function takes the user input as input and checks if it exactly matches any key in the knowledge base. If there is a match, it returns the corresponding value. If there is no exact match, it returns the default response.The
displayMessage()function takes a message and a sender (either "user" or "bot") as input. It creates a new message element with a class based on the sender, sets the text of the message element, and appends the message element to the chatlog element.