0

If I have a radio button group, how can I set the checked property for a given value?

For example

<input type="radio" name="group" value="one" checked>
<input type="radio" name="group" value="two">

If I then wanted to check the second radio button with value 'two' through script, how?

Ed Chipo
  • 3
  • 1
  • Does this answer your question? [Check a radio button with javascript](https://stackoverflow.com/questions/21166860/check-a-radio-button-with-javascript) – Justinas Jul 28 '20 at 11:02

2 Answers2

0

You first need to create unique IDs for both radio inputs.

<input type="radio" name="group" value="one" id="inputOne"checked>
<input type="radio" name="group" value="two" id="inputTwo">

Then you can simply set the checked value to true.

document.getElementById("inputTwo").checked = true;
jsub
  • 150
  • 10
  • No because my elements do not have IDs. They are dynamically created, I could throw on some index'd IDs, but is it possible without IDs? – Ed Chipo Jul 28 '20 at 11:07
  • It would not be possible without IDs since you would need a way to uniquely identify which radio button you want checked. You could create the IDs dynamically as well just as how you created the values "one" and "two" dynamically. – jsub Jul 28 '20 at 11:09
0

This is what you expect?

<input type="radio" name="group" value="one" checked />
<input type="radio" name="group" value="two" />
<script>
  const elements = document.getElementsByTagName('input');
  for (const element of elements) {
    if (element.value === 'two') {
      element.checked = true;
    }
  }
</script>
VnoitKumar
  • 1,350
  • 15
  • 29