0

So before I wrote this code with all my inputs as checkboxes and it worked 100% fine when I click or unclick the options.

My problem is that I changed some of my inputs to radio buttons and now the bottom half of my code doesn't work the same.

If I were to click one a radio button it would show the value of 10, but if I click it again, it will say 20, then I can continue clicking it infinitely and it keeps adding the value to 100000 instead of simply going from 0 to 10 back to 0.

document.addEventListener("click", ({ target }) => {
  if (target.className === "class1" && target.checked) {
    window.menuItems += parseInt(target.value);
  } else if (target.className === "class1" && !target.checked) {
    window.menuItems -= parseInt(target.value);


// this logic below for my radio buttons doesn't work the same 

      } else if (target.className === "radio1" && target.checked) {
        window.tip += parseInt(target.value);
      } else if (target.className === "radio1" && !target.checked) {
        window.tip -= parseInt(target.value);
      } else {
        return;
      }

Is there a built in function to check if a radio input is selected?

Because using target.checked doesn't work the same for radio buttons and I also tried just target but that didn't do the same effect.

Jonas
  • 121,568
  • 97
  • 310
  • 388
makerbaker
  • 180
  • 9

1 Answers1

-1

I think this eventListener now fires on all radio buttons, try settings it only for the radio buttons via class name:

document.querySelector(".class1, .radio1").addEventListener("click", function(event) {

and stop the propagation

event.stopPropagation();
Thyran
  • 84
  • 2
  • I don't get what you wrote? you just wrote an empty function? – makerbaker Jun 09 '22 at 09:45
  • That is just the upper part of the function, the rest can stay the same, except the event.stopPropagation() needs to be implemented in your function as well. And target has to be set via e.target: let target = e.target; – Thyran Jun 09 '22 at 09:48
  • the top function works fine, the issue is radio buttons don't have an inbuilt function called checked, like checkboxes do, so I don't know how to change that – makerbaker Jun 09 '22 at 09:49
  • https://stackoverflow.com/questions/1423777/how-can-i-check-whether-a-radio-button-is-selected-with-javascript – Thyran Jun 09 '22 at 09:50
  • I already get the value of my radio button when I click it, my issue is that clicking it again when it's already selected adds the value instead of subtracting it – makerbaker Jun 09 '22 at 09:57