mercredi 25 septembre 2019

How to enable/disable javascript functions with a checkbox

Hello stackoverflow,

How would I make it possible to (temporarily) disable/enable javascript functions for a with a checkbox.

I want to be able to check a box enabling only one, or both of the functions (including the myScrambleFunction and myConvertFunction) the myConvertFunction capitalizes every odd letter, and the myScrambleFunction scrambles up each word a bit. Sometimes I'd like to only use the scramble function (without the capitalize function) and the other way around.

Any suggestions and examples will be greatly appreciated :)

This: https://jsfiddle.net/MysteriousDuck/3pndLbgq/3/ is what I have right now.

I have tried googling this problem but could not find a solution that suits my needs.


<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" onclick="myConvertFunction(); myScrambleFunction(text);">Convert</button>
        <textarea type="text" placeholder="CoNvErTeD tExT" id="converted" value="Clear" readonly="true" spellcheck="false" style="width: 300px;"></textarea>
            <button class="button button1" onclick="myCopyFunction(); eraseText();">Copy</button>

    </div>
</body>

</html>
/* Made by MysteriousDuck#5764 */

function myConvertFunction() {
    var x = document.getElementById("inputText").value;
    var letters = x.split("");
    var string = "";
    for (i = 0; i < letters.length; i++) {
        if (i % 2 == 0) {
            string += letters[i].toUpperCase();
        } else {
            string += letters[i];
        }
    }
    document.getElementById("converted").value = myScrambleFunction(string);
}

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

function eraseText() {
    document.getElementById("converted").value = "";
    document.getElementById("inputText").value = "";
    document.getElementById("inputText").focus();
}

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(' ');
}



Aucun commentaire:

Enregistrer un commentaire