skip to Main Content

javascript code (the error code is placed at addEventListener)

const translations = {
    en: {
        text1: "testing"
    },
    no: {
        text1: "testing"
    },
    gm: {
        text1: "testen"
    }
}


const languageSelectop = document.querySelector("LS");

problem being around here

languageSelectop.addEventListener("change", (event) => {
    setLanguage(event.target.value)
})
const setLanguage = (language) => {
    if(language == "no"){
        console.log(language);
    }else if(language == "en"){
        console.log(language)
    }else if(language == "gm"){
        console.log(language)
    }
}

html code (no aperent isues as far as i know)

<!DOCTYPE html>
<html lang="en">
    <head>
        <title>Arctic Fox Web - WIP</title>
        <script type="text/javascript" src="js/Language.js"></script>
        
    </head>
    <body>

        <div>
            <select name="" id="LS">
                <option value="en">English</option>
                <option value="no">Norsk</option>
                <option value="gm">Deutsch</option>
            </select>

        </div>

        <div>
            testing
        </div>
        <div>
            testing
        </div>
    
    </body>
</html>

im following a tutorial on yt thus i dont quite know whats wrong if it is needed here is the video Youtube

2

Answers


  1. Issue in this line const languageSelectop = document.querySelector("LS");.
    ID selectors start with # and class selector start with .
    Right version of your line is const languageSelectop = document.querySelector("#LS");.
    More details about selectors here CSS selectors

    Login or Signup to reply.
  2. Here is a working snippet illustrating some of the points in the comments. You don’t really need an if/else structure if the actions are the same but work on different data. I used the ?? operator to provide a fallback solution in case an option was picked for which there is no translation object available.

    const translations = {
      en:{text1: "testing"},
      no:{text1: "testing norsk"},
      gm:{text1: "testen auf deutsch"}};
    
    const sel=document.getElementById("languageSel");
    sel.addEventListener("change",()=>{
     console.log((translations[sel.value]??translations.en).text1);
    });
    <div>
     <select id="languageSel">
      <option value="en">English</option>
      <option value="no">Norsk</option>
      <option value="gm">Deutsch</option>
      <option value="ar">Arabic</option>
     </select>
    </div>
    <div> testing </div>
    <div> testing </div>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search