skip to Main Content

i want to click a radio element automatically with js. Element selection is perfect because when i try to change it with innerHTML, it changes but click() does not work.

Code:

document.addEventListener("DOMContentLoaded", function(){
    document.querySelector(".jet-radio-list__label").innerHTML = "Changed!"
    document.querySelector(".jet-radio-list__label").click()
}

Tried Alternatives like:

document.querySelectorAll('input[type="radio"]').checked = true;

My DOM element which I want to target:
enter image description here

2

Answers


  1. You cannot click a radio button, but you can set the element to "checked". And then you can dispatch an event if that is needed.

    document.addEventListener('DOMContentLoaded', e => {
      document.forms.test.radio01.addEventListener('change', e => {
        console.log(e.target);
      });
    
      document.forms.test.radio01.checked = true;
      let change_event = new Event('change');
      document.forms.test.radio01.dispatchEvent(change_event);
    });
    <form name="test">
      <label id="label01">Radio01: <input type="radio" name="radio01" /></label>
    </form>
    Login or Signup to reply.
  2. Maybe something like the following?:

    document.addEventListener("DOMContentLoaded", function() {
        document.querySelectorAll('input[type="radio"]').forEach(
          (input) => input.checked = true
        );
    });
    label { display: block; }
    <form>
      <label>Radio 1 (field1) <input type="radio" name="field1" value="1" /></label>
      <label>Radio 2 (field1) <input type="radio" name="field1" value="2" /></label>
      <br />
      <label>Radio 3 (field2) <input type="radio" name="field2" value="3" /></label>
    </form>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search