简体   繁体   中英

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

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>

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM