Search code examples
javascripthtmllatin

Pig Latin Translator won’t write results?


I’m trying to write a pig latin translator, but my webpage keeps displaying undefined, and it can’t read from the textarea. The html looks okay, but the text from the textarea that the end user needs inputs is not displayed correctly. I tried changing the textarea’s text by using .textContent, value, and many others.

var textarea = document.getElementById("piglatin");
var button = document.getElementById("click_to_translate");
var translation = document.getElementById("translation");
var toPigLatin = function(str){
    str=str.replace(/([^aeiou]*)([aeiou])(\w+)/, "$2$3$1ay");
};
button.onclick = function(){
    translation.innerHTML = toPigLatin(textarea.textContent);
};
<html lang="en">
    <head>
        <meta charset="UTF-8"/>
        <script src="pig_latin.js"></script>
    </head>
    
    <body>
        <div id="wrapper">
            <h1 id="translation">
                PigLatin Translator!
            </h1>
            <textarea rows="1" cols="30" id="piglatin"></textarea>
            <button type="button" id="click_to_translate">Translate</button>
        </div>
    </body>
    
</html>

I’m about to give up at this point, and it would be appreciated if someone could help.


Solution

  • There were two issues: The function toPigLatin should return the appropriate result, instead of setting str=.... Also, the value of a text area is textarea.value.

    var textarea = document.getElementById("piglatin");
    var button = document.getElementById("click_to_translate");
    var translation = document.getElementById("translation");
    var toPigLatin = function(str){
        return str.replace(/([^aeiou]*)([aeiou])(\w+)/, "$2$3$1ay");
    };
    button.onclick = function(){
        translation.innerHTML = toPigLatin(textarea.value);
    };
    <html lang="en">
        <head>
            <meta charset="UTF-8"/>
            <script src="pig_latin.js"></script>
        </head>
        
        <body>
            <div id="wrapper">
                <h1 id="translation">
                    PigLatin Translator!
                </h1>
                <textarea rows="1" cols="30" id="piglatin"></textarea>
                <button type="button" id="click_to_translate">Translate</button>
            </div>
        </body>
        
    </html>