0

Im trying to reprogram a calculator using the eventListener as it should make the code better overall. However I am having trouble getting the value from the html to use it in the javascript!

Here is the JS Fiddle http://jsfiddle.net/zrm9L0u9/

And here is the code

var input = document.getElementById("calculator").addEventListener("click", calc);


function calc(a) {
    input = this.a;
    console.log(input);
}

Thanks for your time

Adam91Holt
  • 778
  • 1
  • 8
  • 26

3 Answers3

1

You wanted something like this I suppose, calc is passed event object, through which you can take the value.

function calc(a) {
    var input = a.target
    console.log(input.value);
}

Edit:

After seeing fiddle, calculator turned out to be a div, do not know what you're trying to achieve.

Amit Joki
  • 53,955
  • 7
  • 67
  • 89
  • I still get an issue when I click a number I just get undefined as if its passing through no value :S – Adam91Holt Oct 08 '14 at 17:25
  • What I am trying to do is anything in the div 'calculator' once a button is pressed it should then send the value of that button to the function everytime it is clicked. – Adam91Holt Oct 08 '14 at 17:36
0

I think span is not supposed to have 'value' attribute. That's why you can't get it from '.value' Try:

function calc(a) {
    input = a.srcElement;
    console.log(input.getAttribute("value"));
}
Diogo Silva
  • 301
  • 3
  • 8
-1

(this) can be used to access a variable present in an html element, but to get the value of an html element from within a function, you should use .innerHTML.

Here is more about (this). How does the "this" keyword work?

Community
  • 1
  • 1