I know that the below is perfectly viable:
var numberArray = [];
function addNumber(number) {
numberArray.push(number);
}
and then:
<input type="button" value="Save" onclick="addNum(10);">
<input type="button" value="Save" onclick="addNum(990);">
...
But is it possible, for a better code, to have both my array and my action on the same function, and then trigger it on a click event, thus populating my array? Asking because, doing this:
function addNumber(number) {
var numberArray = [];
numberArray.push(number);
}
Does not increase the array values.
I know that inline click events is considerate a bad practice nowadays, but it's for learning purposes. All other answers here reference the array as a global scope, which is what I'm trying to avoid.
Edit: Ok if the above is not possible, any answer avoiding the global scope usage is valid.
You can use a Self-Invoking Function, for creating a local scope, then you can add eventListeners instead using onclick
directive.
(function () {
var numberArray = [];
function addNumber() {
var child = this;
var number = parseInt(child.getAttribute('data-number'), 10);
numberArray.push(number);
console.log(numberArray);
}
var _elms = document.getElementsByClassName('add-number-input');
for (var i = 0; i < _elms.length; i++)
_elms[i].addEventListener('click', addNumber);
})();
Add to a class .add-number-input
to your inputs:
<input class="add-number-input" data-number="10" ...>
<input class="add-number-input" data-number="990" ...>
Now both your array and your function isn't on global scope.
http://codepen.io/rdsedmundo/pen/EgKGXK
It can be achieved using self-invoking function. By this the numberArray
will be in that function's scope and the method addNumber
will be exposed as global.
(function(){
var numberArray = [];
window.addNumber = function(number) {
numberArray.push(number);
}
})();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With