search

Home  >  Q&A  >  body text

Why does the second "checked" in the JavaScript input overwrite the first?

I have a simple question and I hope someone can help me solve it.

I have some Javascript code that is responsible for checking two separate inputs. However, it seems that only one input can be checked.

No matter which input's "check" I put first in Javascript, it gets ignored or overridden, and I don't know why. Only the second input will be checked.

var radioButtonSticky = stickyATC.find('.swatch[data-option-index="' + i + '"] :radio[value="' + variant.options[i] +'"]');

var radioButtonMobileSticky = mobileStickyAtc.find('.swatch-dropdown__sliding-option-selector-outer-container[data-option-index="' + i + '"] :radio[value="' + variant.options[i] +'"]');

radioButtonSticky.get(0).checked = true;
radioButtonMobileSticky.get(0).checked = true;

In the above example, only the "radioButtonMobileSticky" input is selected. However, if I swap the order of the last two lines of this code, only the "radioButtonSticky" input will be selected.

I haven't found any answers online as to why this is happening and I'm going crazy! Thanks for any help!

I would expect both inputs to be selected regardless of the order in which JavaScript/JQuery "checks" them.

P粉225961749P粉225961749440 days ago545

reply all(1)I'll reply

  • P粉081360775

    P粉0813607752023-09-19 10:56:50

    From what I can see from your code snippet: this may happen because you used input[type="radio"] instead of input[type="checkbox" ].

    Only one radio button can be selected in a given group.
    View MDN Web Documentation

    You should consider using checkboxes instead of radio buttons.

    Have a nice day!

    reply
    0
  • Cancelreply