Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

193
Views
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 answers
Answer question

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 Report

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 Report

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!