Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

198
Views
How to execute or stop a function on toggle switch using plain javascript?

So I have this transliteration function which I need to execute if the checkbox is checked. The issue is that, the function continues to run after the checkbox is unchecked as well.

const checkBox = document.querySelector("#checkbox");
const input = document.querySelector("#input");

function transRussian(){
  ch = ch.replace(/l/g, "л");
  ch = ch.replace(/p/g, "п");
  return ch;
}

checkBox.addEventListener('change',()=>{
  if(checkBox.checked){
    transliterate();
  }
  else{
    console.log("transliteration is turned off")
  }
});

input.addEventListener('keyup',()=>{
  var ch = input.value;
  transRussian(ch);
  input.value = ch;
});
<input type="checkbox" id="checkbox">
<input type="text" id="input">

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

In this solution, if the translation checkbox is clicked, the translateBlock() method is called and the text inside the <textarea> element is changed according to the logic.

/* A let variable is declared, not a const, to change the content. */
let checkBox = document.getElementById('checkbox');
let input = document.getElementById('input');

function transRussian(ch){
  ch = ch.replace(/l/g, "л");
  ch = ch.replace(/p/g, "п");
  return ch;
}

function translateBlock(){
  var ch = input.value;
  input.value = transRussian(ch);
}

/* When the checkbox is clicked, the control variable is set to true. */
input.addEventListener('keyup', () => {
  if(checkBox.checked)
    translateBlock();
});

/* This method is triggered when data is entered in the <textarea> element. */
checkBox.addEventListener('change', () => {
  if(checkBox.checked)
    translateBlock();
  else
    console.log("transliteration is turned off")
});
textarea{
  display: block;
}
<span>Translate</span>
<input type="checkbox" id="checkbox"/>

<textarea id="input" name="w3review" rows="4" cols="50">
At w3schools.com you will learn how to make a website. They offer free tutorials in all web development technologies.
</textarea>

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!