TransWikia.com

How to change radio button checked attribute

Stack Overflow Asked by White Death on November 7, 2021

what I am trying to do is to write a function that selects a radio button,
here is a codepen:

Codepen radio button Test

function select(valueOfRadio) {
    $('#s1').removeAttr('checked')
    $('#s2').removeAttr('checked')
    $('#s3').removeAttr('checked')
    switch (valueOfRadio) {// if it equals 
        case 2:
            document.getElementById('s2').setAttribute('checked', true)
            break;
        case 3:
            document.getElementById('s3').setAttribute('checked', true)
            break;
        default:
            document.getElementById('s1').setAttribute('checked', true)
    }
}

– the problem is that the `attr()` function doesn’t work after pressing the radio button manually.

– after searching online I found that the attr() function works only to set initial values and that it can’t be used after the user interacts with the element. so I tried the native `setAttribute()` but it didn’t work either. then I found that I could use the jquery `val()` function, but I don’t want to change the value of the radio button input, I want to change the `checked` attribute.
**my question is:**
how to change the checked attribute of radio button input without `attr()` function?

2 Answers

As requested in the comments, here's my solution:

function select(valueOfRadio){
  $('#s1').prop('checked')
  $('#s2').prop('checked')
  $('#s3').prop('checked')
  switch(valueOfRadio){ // if it equals 
    case 2 :
      $('#s2').prop('checked', true);
      break;
    case 3 :
      $('#s3').prop('checked', true);
      break;
    default:
      $('#s1').prop('checked', true);
  }
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
  <table>
    <tr id="defaultSize">
      <th><input type="radio" name="size" value="1" id="s1"/></th>
      <th><input type="radio" name="size" value="2" id="s2"/></th>
      <th><input type="radio" name="size" value="3" id="s3"/></th>
    </tr>
  </table>

Answered by xKobalt on November 7, 2021

When you check a radio button by setting the .checked attribute to true it set every other radio button with the same name attribute to unchecked

function select(value) {
  document.getElementById(`s${value}`).checked = true
}
let i = 1
setInterval(
  () => {select(i++ % 3 + 1)},
  1000
)
<input type="radio" id="s1" name="test" checked>1</input>
<input type="radio" id="s2" name="test">2</input>
<input type="radio" id="s3" name="test">3</input>

Answered by jonatjano on November 7, 2021

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP