简体   繁体   中英

How to insert my text from an input field into a Javascript template literal but the result is undefined

I created an input field where you can enter text and I'm trying to insert that text into a template literal. I then want to use them in other scripts. The issue I'm facing is that after getting the text from the input field and assigning it to a variable, I then put that variable into the template literal and get 'undefined' instead of the text I typed in. Any ideas why this could be happening and ways to solve it? Thanks in advance.

Here's the html code:

<label style="color:black;">Enter words:</label>
<input type="text" name="" id="myText"><br>
<button id="myButton">Button</button>
    
<button onclick="zipFile()">Download Button</button>
    
<script src="https://cdnjs.cloudflare.com/ajax/libs/jszip/3.7.1/jszip.min.js"></script>
<script src="http://cdn.jsdelivr.net/g/filesaver.js"></script>

Here's the javascript

let inputText = "originalText";
        document.getElementById("myButton").onclick = function (){getMyName()};
        function getMyName(){
            inputText = document.getElementById("myText").value;
            console.log("This is input Text: ", inputText);    
            console.log("This is input text but from scriptTemplate " + scriptTemplate);
        }

        const scriptTemplate = `
        ${inputText};
    `;
        
        var zip = new JSZip();
        
        function zipFile(){
            zip.file("script.js", scriptTemplate);
        
            zip.generateAsync({type:"blob"})
            .then(function(content){
                saveAs(content, "test1.zip");
            });
        }

You are creating the scriptTemplate value on script initialization while you should try creating it from within the function itself. This way it gets created after every call to zipFile :

    function zipFile(){
        const scriptTemplate = `
          ${inputText};
        `;
        zip.file("script.js", scriptTemplate);
    
        zip.generateAsync({type:"blob"})
        .then(function(content){
            saveAs(content, "test1.zip");
        });
    }

Your issue here is that you're declaring scriptTemplate outside any function body. That means it gets run when the script first gets loaded to the page, but it isn't part of the function which gets run when you click on a button. I would try adding returns to your functions, lose the name-getting button, and then calling the getMyName function when the user goes to download it.

 const zip = new JSZip(); function getMyName() { const inputText = document.getElementById("myText").value; console.log("This is input Text: ", inputText); return inputText; } function zipFile() { const inputText = getMyName(); const scriptTemplate = ` ${inputText}; `; console.log("This is input text but from scriptTemplate " + scriptTemplate); zip.file("script.js", scriptTemplate); zip.generateAsync({ type: "blob" }) .then(function (content) { saveAs(content, "test1.zip"); }); }
 <label>Enter words:</label> <input type="text" id="myText"><br> <button onclick="zipFile()">Download Button</button> <script src="https://cdnjs.cloudflare.com/ajax/libs/jszip/3.7.1/jszip.min.js"></script> <script src="http://cdn.jsdelivr.net/g/filesaver.js"></script>

Surely you get originalText when outputting scriptTemplate ?

Maybe you were having higher hopes for how template literals work. They do not produce some new magical functional string type that result in different values whenever they are accessed. They just produce strings. Although it is possible to create "custom" template literals, so called tagged templates, that can produce whatever you decide, and if you manage to engineer some cool return value bound to some other value, that would be overengineering to say the least.

  • Do you need the myButton for some reason? If not just read the input when clicking the download button.
  • Otherwise, a shared variable is indeed an option, you don't need template literals for that.
  • Another option is to use a hidden input field and set its value when myButton is clicked and read from it when you need the value (ie clicking the download button)

Happy coding!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM