Working on TOD calculator project. While I likely have other potential errors in my code, I am only seeking to understand getting the button number/value into the function. I think I need to get the button value assigned so that the xyz function can process it. Is it even necessary to add the value attribute to a CSS button in this instance?
<div >
<button value="7">7</button>
<button value="8">8</button>
<button value="9">9</button>
<button value="*">*</button>
</div>
let buttons = document.getElementsByClassName("btn");
for (let i = 0; i < buttons.length; i = 1) {
buttons[i].addEventListener("click", xyz);
function xyz(x) {
let nbr1 = "0";
let operator = "";
let nbr2 = "0";
const sum = maths(nbr1, operator, nbr2);
if (x == "=") button.value = sum;
if (x == " " || "-" || "*" || "/") x = operator;
if (operator == null) x = nbr1;
else x = nbr2;
console.log(nbr1, operator, nbr2);
}
}
document.getElementsByClassName("btn").value
causes an
uncaught typeError: buttons is undefined
Without .values
the function runs without errors, but none
of the values get assigned.
I have tried:
getAttributes(‘value’)
and get: "not a function" typeError.- a number of different iterations in the (xyz) of lines such as: x, buttons, buttons.value etc.
CodePudding user response:
First of all, you are redefining the function in every iteration of the loop (not necessary and not optimal). Just define the function before you start the loop.
The event handler will be passed the event object as the parameter. The event.target
points to the actual clicked-on element which may be a child of the button, while event.currentTarget
will be the element the handler was assigned to (the button itself).
If you only have the button value nested inside it then you can use event.currentTarget.innerText
instead of event.currentTarget.value
to get the value attribute.
let buttons = document.getElementsByClassName("btn");
function xyz(event) {
const btnVal = event.currentTarget.innerText
console.log(btnVal);
}
for (let i = 0; i < buttons.length; i = 1) {
buttons[i].addEventListener("click", xyz);
}
<div >
<button >7</button>
<button >8</button>
<button >9</button>
<button >*</button>
</div>