如何使用单行 javascript(无 jQuery)检查没有 id 的单选按钮?

How can I check a radio button with no id using a single line of javascript (no jQuery)?

好的,这是初学者提出的一个非常具体的问题,请耐心等待。

我是刚入门的新手。这是背景(如果你不在乎,请跳到下一段):我正在更新我的第一个 android 应用程序,我正在使用 MIT App Inventor 2 to do it. It's a free tool online that uses a WYSIWYG screen editor and Blockly to create behaviors, interactions, etc. The app I'm making loads a specific web page with a form and fills out most of the form for you (specifically, it's to help people enter the online ticket lottery for a theater show). The page is not my own so I can't edit the HTML. But I can run javascript on top of it by plugging single lines of javascript code into the Blockly side of App Inventor. Here's a relevant example of how it looks.

我已经知道如何使用 getElementByID() 填写大部分表单。但是有一组没有 id 的单选按钮。这是 HTML 的轻微修改版本(我无法编辑):

<div id="cont_id_tickets">
    <div>
        <input type="radio" name="tickets" value="1" />
        <span style="font-family:Times New Roman; font-size:15px;">1</span>
    </div>
    <div>
        <input type="radio" name="tickets" value="2" />
        <span style="font-family:Times New Roman; font-size:15px;">2</span>
    </div>
    <div id="required_info_tickets" class="requiredInfo floatLeft">
    </div>
    <input type="hidden" name="reqField" value="tickets" alt="Radio" req="true" errorMsg="Please enter a valid value." requredErrorMsg="This field is required. Please enter a value."
        patternID="0" customRegex="" />
</div>

我使用以下方法取得了一些进展:

document.querySelector('input[name=tickets]').checked = true;

但那当然只是 select 第一个单选按钮。我希望能够获得一个值(1 或 2)并相应地使其 select 成为正确的按钮。我正在使用的 Blockly 后端允许我定义一个变量以插入 javascript 行,但 javascript 行本身必须基本上是一行。例如,如果我希望值为 2,我希望以下方法之一可以工作:

document.querySelector('input[name=tickets][value=2]').checked = true;
document.querySelector('input[name=tickets]').2.checked = true;

但也没有。关于正确语法的任何想法?

谢谢!

您需要将您尝试 select 使用的值放在引号中:

document.querySelector('input[name=tickets][value="2"]').checked = true;

例子

document.querySelector('input[name=tickets][value="2"]').checked = true;
<div id="cont_id_tickets">
  <div>
    <input type="radio" name="tickets" value="1" />
    <span style="font-family:Times New Roman; font-size:15px;">1</span>
  </div>
  <div>
    <input type="radio" name="tickets" value="2" />
    <span style="font-family:Times New Roman; font-size:15px;">2</span>
  </div>
  <div id="required_info_tickets" class="requiredInfo floatLeft">
  </div>
  <input type="hidden" name="reqField" value="tickets" alt="Radio" req="true" errorMsg="Please enter a valid value." requredErrorMsg="This field is required. Please enter a value." patternID="0" customRegex="" />
</div>