skip to Main Content

I am trying to create a basic translator where the script will translate between Turkish and English, but while I was trying to create the program, I got stuck at a point. I have 2 select elements.

When the select element with the id of "languages" option is English I want the select element with the id of "languagesT" to be Turkish and the same when I select Turkish in languages. So basically I want them to be opposite, and this is what I have done so far with javascript:

const translating = document.getElementById("languages")
const translator = document.getElementById("languagesT")

translating.addEventListener("change", () => {
    if (translating.value === "turkish") {
      translator.value = "english";
    }
    else if (translating.value === "english") {
      translator.value = "turkish";
    }
  }
);
<select name="languages" id="languages">
    <option value="english">English</option>
    <option value="turkish">Turkish</option>
</select>
<select name="languagesT" id="languagesT">
    <option value="turkish">Turkish</option>
    <option value="english">English</option>
</select>

2

Answers


  1. Your javascript code looks correct; there’s a typo in your HTML code in the second option value of the second select element.

    <select name="languagesT" id="languagesT">
        <option value="turkish">Turkish</option>
        <option value="englisih">English</option>
    </select>
    

    it should be

    <select name="languagesT" id="languagesT">
        <option value="turkish">Turkish</option>
        <option value="english">English</option>
    </select>
    
    Login or Signup to reply.
  2. You could fix your spelling or delegate

    Here we do not care what the languages are

    document.getElementById("languages").addEventListener("change", (e) => {
      const tgt = e.target;
      const value = tgt.value;
      e.currentTarget.querySelectorAll("select").forEach(sel => {
        if (tgt!==sel) sel.selectedIndex = tgt.selectedIndex === 0 ? 0 : 1;
      });  
    });
    <div id="languages">
    <select name="language1" id="en_tr">
        <option value="english" selected>English</option>
        <option value="turkish">Turkish</option>
    </select>
    <select name="language2" id="tr_en">
        <option value="turkish"selected>Turkish</option>
        <option value="english">English</option>
    </select>
    </div>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search