How to pass in variables inside function calls at onclick?

Viewed 66

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.

4 Answers

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>

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.

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>

Because onclick is a javascript function, you can use javascript inside of it like that :

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

But you can't use javascript stored variable inside html. But you can use function that returns the value you want :

function evaluat(expr){
  console.log(eval(expr));
}

var parse = function () {
  return document.querySelector('input').value.replace('/\^/','**');
};

var parse2 = document.querySelector('input').value.replace('/\^/','**')
<input></input>
<p><button onclick="evaluat(parse())">Replace</button></p> <!-- OK -->
<p><button onclick="evaluat(parse2)">Replace</button></p> <!-- undefined -->

Related