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

196
Visualizações
How to pass in variables inside function calls at onclick?

I have a doubt as to how to pass variables into a function call that is inside an onclick attribute. It's actually a bad practice but I still want to know in case I ever need.

For Example:

let parsed = document.querySelector('input').value.replace('/\^/','**');
function evaluat(expr){
    console.log(eval(expr));
  }
<input></input>
<p><button onclick="evaluat(parsed)">Compute</button></p>

This code prints undefined for the input 5^2 instead of the expected 25.

about 4 years ago · Juan Pablo Isaza
3 Respostas
Responde à pergunta

0

Maybe use a closure, and pass in the input to the function that's returned as the click listener.

const input = document.querySelector('input');
const button = document.querySelector('button');

button.addEventListener('click', evaluat(input), false);

function evaluat(input) {
  return function () {
    const str = input.value.replace('^', '**');
    console.log(eval(str));
  }
}
<input></input>
<p><button>Replace</button></p>

about 4 years ago · Juan Pablo Isaza Relatório

0

Assuming that you start your page with the input empty, the parsed variable has already been evaluated to ''. In your evaluat (should be evaluate) function, you haven't retrieved the value of document.querySelector('input').value again, so the function has evaled an empty string, which is why it logs undefined.

You'll need to make changes to the function to be something like...

function evaluat() {
  console.log(
    eval(document.querySelector('input').value.replace(/\^/,'**'))
  );
}

You won't have to pass any arguments into this function, since it will query the DOM each time it is executed.

By the way, note that eval() is dangerous. Avoid using it.

about 4 years ago · Juan Pablo Isaza Relatório

0

It is recommended that you give your element a unique id to avoid ambiguity.

function evaluat(expr) {
  let val = document.getElementById('parsed').value.replace('^', '**');
  console.log(eval(val));
}
<input id="parsed"></input>
<p><button  onclick="evaluat()">Replace</button></p>

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