Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

124
Visualizações
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");
            });
        }
about 4 years ago · Juan Pablo Isaza
3 Respostas
Responde à pergunta

0

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");
        });
    }
about 4 years ago · Juan Pablo Isaza Relatório

0

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>

about 4 years ago · Juan Pablo Isaza Relatório

0

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 (i.e. clicking the download button)

Happy coding!

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda