Как подключить функции JS к флажку - PullRequest
1 голос
/ 26 сентября 2019

Здравствуйте,

Я создаю простой веб-сайт для смены текста, на котором я хочу, чтобы пользователь мог выбирать, какие опции использовать.Прямо сейчас у меня есть два варианта;myConvertOption, который использует заглавные буквы в слове, и у меня есть myScrambleOption, который случайным образом смешивает каждое слово.

Прямо сейчас, когда вы нажимаете Caps (checkbox_1), он уже выполняет функцию, в которой я хочу, чтобы она выполнялась только тогда, когда пользователь нажимает кнопку «Преобразовать» +, теперь он также ставит пробелы между каждой буквой.Кнопка Scramble (checkbox_2) по какой-то причине ничего не делает, за исключением того, что консоль регистрирует изменения.

JSfiddle: https://jsfiddle.net/MysteriousDuck/hLjytr2p/1/

Любая помощь и предложения будут высоко оценены!

PS Я новичок в Javascript.

Флажок прослушивателей событий:

checkbox_1.addEventListener('change', function () {
    console.log("checkbox_1 changed");
    if (this.checked) {
        myConvertFunction();
    } else {
        //Do nothing
    }
})

checkbox_2.addEventListener('change', function () {
    console.log("checkbox_2 changed");
    if (this.checked) {
        myScrambleFunction(text);
    } else {
        //Do nothing
    }
})

Флажок HTML:

        <div class="checkbox">
            <input type="checkbox" id="checkbox_1" >
            <label for="checkbox_1">Caps</label>
        </div>
        <div class="checkbox">
            <input type="checkbox" id="checkbox_2" >
            <label for="checkbox_2">Scramble</label>
        </div> 

Ответы [ 2 ]

1 голос
/ 26 сентября 2019

это работает правильно ..Вам просто нужно было добавить событие на кнопку и затем проверить, какой флажок был установлен, и другие мелочи

<!doctype html>
<html>

<head>

</head>

<body>

  <div class="container">

    <h1> Text Changer </h1>
    <h2> CAPS + randomize letters text changer</h2>
    <div class="checkbox">
      <input type="checkbox" id="checkbox_1">
      <label for="checkbox_1">Caps</label>
    </div>
    <div class="checkbox">
      <input type="checkbox" id="checkbox_2">
      <label for="checkbox_2">Scramble</label>
    </div>



    <textarea type="text" autofocus="true" placeholder="input text" id="inputText" value="Input Value" spellcheck="false" style="width: 300px;"></textarea>
    <button class="button button1" id="convertText">Convert</button>
    <textarea type="text" placeholder="converted text" id="convertedText" value="Clear" readonly="true" spellcheck="false" style="width: 300px;"></textarea>
    <button class="button button1" id="copyText">Copy</button>

  </div>

  <script>
    var text = document.getElementById("inputText").value;
    var convertText = document.getElementById("convertText");
    var checkbox_2 = document.getElementById("checkbox_2");
    var checkbox_1 = document.getElementById("checkbox_1");

    //Capitalize every odd letter
    function myConvertFunction() {
      var x = document.getElementById("inputText").value;
      var string = "";
      for (let i = 0; i < x.length; i++) {
        if (i % 2 == 0) {
          string = string + x[i].toUpperCase();
        } else {
          string = string + x[i];;
        }
      }
      return string;
    }

    //Scramble words
    function myScrambleFunction(text) {
      let words = text.split(" ");
      words = words.map(word => {
        if (word.length >= 3) {
          return word.split('').sort(() => 0.7 - Math.random()).join('');
        }
        return word;
      });
      return words.join(' ');
    }

    document.getElementById("copyText").addEventListener("click", myCopyFunction);

    //Copy textarea output
    function myCopyFunction() {
      var copyText = document.getElementById("convertedText");
      copyText.select();
      document.execCommand("copy");
      alert("Copied the text: " + copyText.value);
      eraseText();
    }

    //Delete textarea output
    function eraseText() {
      document.getElementById("convertedText").value = "";
      document.getElementById("inputText").value = "";
      document.getElementById("inputText").focus();
    }


    //don't add the event to the radio buttons (previously checkboxes), add it to the convert button, and in its function test which radio button has been checked
    convertText.addEventListener('click', function() {
      if (checkbox_1.checked && checkbox_2.checked) {
        console.log("doing both options");
        document.getElementById("convertedText").value = myScrambleFunction(myConvertFunction());
      } else if (checkbox_2.checked) {
        console.log("proceeding scrumble");
        document.getElementById("convertedText").value = myScrambleFunction(text);
      } else if (checkbox_1.checked) {
        console.log("proceeding cap");
        document.getElementById("convertedText").value = myConvertFunction();
      }
    })
  </script>


</body>

</html>
0 голосов
/ 26 сентября 2019

Вы никогда не обновляете var text.

Вам необходимо обновить его перед использованием, если вы хотите, чтобы значение было чем-то отличным от пустой строки.

checkbox_2.addEventListener('change', function () {
    console.log("checkbox_2 changed");
    if (this.checked) {
        text = document.getElementById("inputText").value;
        myScrambleFunction(text);
    } else {
        //Do nothing
    }
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...