0

I'm trying to add arrays into onclick button for my simple JavaScript calculator.

My first try was that process(text[i]); in the code but it doesn't work at all.

So, I converted the array item to string and gave to the onclick function. then it runs a strange way.

Would you let me know how I can pass to correct type?

var text = ["+", "-", "*", "/", "SQRT", "POW", "RNDM", "MAX", "MIN"];

for (var i = 0; i < text.length; i++) {
  var child = document.createElement('button');
  child.innerText = text[i];
  child.value = text[i];
  var temp = text[i].toString();   //<-- convert to make sure it is string

  child.onclick = function () {                
    process(temp);   //<-- it doesn't work properly, and it won't accept "process(text[i])???".
  }

  label1.appendChild(child);
}        

document.body.appendChild(label1);

2 Answers 2

1

I have to step away from my computer, but below is almost working. ops is undefined once it gets into the onclick being set. Not sure why. Hopefully somebody else can build off of this.

function process(operation) {
  alert(operation);
}

var ops = ["+", "-", "*", "/", "SQRT", "POW", "RNDM", "MAX", "MIN"];

for (var i = 0; i < ops.length; i++) {
  var child = document.createElement('button');
  child.innerText = ops[i];
  child.value = ops[i];

  (child.onclick = function() {

    process(ops[i]);
  })(i)

  // label1.appendChild(child);
  document.body.appendChild(child);
}

// document.body.appendChild(label1);

Sign up to request clarification or add additional context in comments.

2 Comments

I added the enclose of "function (i)" in your code as adeneo's suggestion. then it is also working fine. Thanks.
@tomtom, excellent. Can you click the check mark below the arrows on the left to indicate this answer was the solution to your question?
0

As already well explained by @adeneo, the problem is that all onclick handlers use the same temp variable. One more way of providing a separate scope for each iteration, is to use forEach method instead of for loop:

["+", "-", "*", "/", "SQRT", "POW", "RNDM", "MAX", "MIN"].forEach(function(text) {
    var child = document.createElement('button');
    child.innerText = text;
    child.value = text;
    child.onclick = function () {
        process(text);
    }
    label1.appendChild(child);
});

Sample: http://jsfiddle.net/kq1mpm3g/

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.