Home > database >  How to check a radio button with JavaScript Pure? Use Form id=value
How to check a radio button with JavaScript Pure? Use Form id=value

Time:05-19

I need to define a radio input with Name='status' and Value='X' in a form with id='A'. Just like setting selected, in a Value='X' in a form with id='B'.

document.querySelector("form[id='A'] input[name='status'][value=1]").checked = true;

document.querySelector("form[id='B'] select[id='cars'][value=volvo]").selected = true;

document.querySelector("form[id='C'] input[name='status'][value=2]").checked = true;
<form id='A'>
  FROM A - Radio Test checked: <br>
        Value 1 <input type='radio' name='status' value='1' /> <br>
        Value 2 <input type='radio' name='status' value='2' /> <br>
        Value 3 <input type='radio' name='status' value='3' /> 
</form>
<hr>
<form id='B'>
  FROM B - Select Test selected: <br>
        <select id="cars">
          <option value="volvo">Volvo</option>
          <option value="saab">Saab</option>
          <option value="vw">VW</option>
          <option value="audi" selected>Audi</option>
        </select>
</form>
<hr>
<form id='C'>
  FROM C - Radio Test checked: <br>
        Value 1 <input type='radio' name='status' value='1' /> <br>
        Value 2 <input type='radio' name='status' value='2' /> <br>
        Value 3 <input type='radio' name='status' value='3' /> 
</form>

CodePudding user response:

Try this

document.querySelector("form[id='A']  input[name='status'][value='1']").checked = true;

instead of this

document.querySelector("form[id='A']  input[name='status'][value=1]").checked = true;

you have to quote the value

  • Related