Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

195
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

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 Denunciar

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda