Home > Software design >  Trouble outputting link within JS
Trouble outputting link within JS

Time:09-17

I'm playing around learning how to create a very simple HTML, CSS, JS chat bot and I've ran into some trouble which I'm hoping someone could help me with.

When I type in "Hey" it outputs "Hello!" as expected, but when I try my "test link" response I can't figure out how to display it. Any ideas what I could be doing wrong? To clarify, when the user types in "test link" I want it to output "I can help you find what you're looking for. Click Here!" with "Click Here!" being a link to google.com.

Any help would be much appreciated!

<script> 
function talk(){    
var know = {        
    "Hey":"Hello!",
        
    "test link":"I can help you find what you're looking for."   <a href="https://www.google.com/">Click Here!</a>  
    
};

var user = document.getElementById('userBox').value;
document.getElementById('chatLog').innerHTML = user   "<br>";
if(user in know){
    document.getElementById('chatLog').innerHTML = know[user]   "<br>";
}else{
    document.getElementById('chatLog').innerHTML = "I do not understand.";
}
}

</script>

CodePudding user response:

Your test link value is not a single string because your quotation marks are not around the whole property value. Try this: "test link":`I can help you find what you're looking for. <a href="https://www.google.com/">Click Here!</a>`

CodePudding user response:

  • You cannot nest the same quotes without escaping them or using template literals (backticks)

    "test link": `I can help you find what you're looking for. <a href="https://www.google.com/">Click Here!</a>`
    

    See the working example in my snippet below:

  • I recommend event listeners instead of click handlers

  • if you wrap in a form, enter will run the function

Type test link into the field to see the link

const know = {
  "hey": "Hello! Type <span class=\"cursive\">test link</span> to see the link",
  "test link": `I can help you find what you're looking for. <a href="https://www.google.com/">Click Here!</a>`
};

window.addEventListener("load", function() { // when page loads
  document.getElementById("testForm").addEventListener("submit", function(e) { // pass the event
    e.preventDefault(); // so we can block the submit

    const user = document.getElementById('userBox').value.toLowerCase(); // handle hey AND HEY and Hey
    document.getElementById('chatLog').innerHTML = user   "<br>";
    if (user in know) {
      document.getElementById('chatLog').innerHTML = know[user]   "<br>";
    } else {
      document.getElementById('chatLog').innerHTML = "I do not understand.";
    }
  })
})
.cursive { color: red; font-style: italic; }
<form id="testForm">
  <input type="text" id="userBox" />
</form>

<div id="chatLog"></div>

  • Related