0

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

  • Could you add the HTML for the radio buttons? – Ben Stephens May 18 '21 at 10:49
  • `querySelectorAll` returns array, so `querySelectorAll()[0].checked = true`. Better use proper ID's for each radio button – Justinas May 18 '21 at 10:51
  • Added DOM image in the question. Please review. Its wordpress so please keep in mind that i do not have much control over HTML. – Zaeem Javed May 18 '21 at 11:03
  • @Justinas I totally have 2 radio inputs on whole page & I want both of them to get this js applied. I do not have control over HTML because i am using wordpress & elementor so we'll need a workaroud maybe. How can i do that? – Zaeem Javed May 18 '21 at 11:06
  • Prefered way as chrwahl mentioned is to check radio button: https://stackoverflow.com/questions/21166860/check-a-radio-button-with-javascript Note: You are also clicking `jet-radio-list__label` instead of `jet-radio-list__input` –  May 18 '21 at 11:21
  • I tried jet-radio-list__input as well but no luck there as well – Zaeem Javed May 18 '21 at 11:28
  • Try to execute the command in console. If it works then there is something wrong with loading of js or something catches the event and discards it. If it does not work tell us what error you get. –  May 18 '21 at 11:41

2 Answers2

0

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>
chrwahl
  • 8,675
  • 2
  • 20
  • 30
0

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>
Ben Stephens
  • 3,303
  • 1
  • 4
  • 8