Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
176 views
in Technique[技术] by (71.8m points)

html - Javascript value of a single radio button

I have a form that can have a varible number of radio buttons. From one to sixteen. I have a switch statement where I want various actions to happen if the user presses a certian button. If they press the number one on the numberic keypad, I want the first radio button to be selected and the form to be submitted.

case 97:
                            document.form_name.radio[0].checked=true;
                            document.form_name.submit();
                            break;

This works when there is more than one radio button in the form but when there is only one, it doesn't work. I can find out before I execute to code how many radio buttons are in the form. What code to I need to use the check the radio button, if it is the only one?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You can use querySelector since it only selects the FIRST anyway. You can also use querySelectorAll and the position in the array to select any other radios also.

document.querySelector("input[name='drop_items']").checked=true;
//document.querySelectorAll("input[name='drop_items']")[1].checked=true;
<input type="radio" name="drop_items" value="1">
<input type="radio" name="drop_items" value="12">

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...