如何在不使用id的情况下选择javascript中的第二个单选按钮

How to select my second radio button in javascript without using id?

本文关键字:选择 情况下 javascript 单选按钮 第二个 id      更新时间:2023-09-26

嘿,我正在做一些事情,但可以也不想更改HTML。无法添加ID按钮。我想选择第二个无线电输入。

这是html:

  <fieldset>
        <legend>I want to sign up:</legend>
        <label>
            <input type="radio" name="submit-for" value="project">
            <span>For project</span>
        </label>
        <label>
           <input type="radio" name="submit-for" value="stage">
           <span>As intern</span>
       </label>
  </fieldset>

以下是我尝试在javascript中选择它的方法,但没有成功:

   document.querySelector('input[type="radio"]:nth-of-type(2)').onclick = function () {
       document.getElementById("project").style.display = 'none';
       document.getElementById("stage").style.display = 'block';
   };

   document.querySelector('input[type="radio"]:nth-child(2)').onclick = function () {
       document.getElementById("project").style.display = 'none';
       document.getElementById("stage").style.display = 'block';
   };

有人能帮忙吗?

您真的想选择"第二个"单选按钮,还是选择"值为'stage'的单选按钮"?第二个选项听起来更具扩展性。

document.querySelector('input[type="radio"][value="stage"]')

编辑:另外,投票支持你的问题,因为你没有使用身份证。无论你是否被迫,始终保持良好的实践。

document.querySelectorAll('fieldset input[type="radio"]')[1]=function () {
  document.getElementById("project").style.display = 'none';
         document.getElementById("stage").style.display = 'block';
    };

您可以使用document.getElementByName并选择集合中的第二个:

document.getElementsByName("submit-for")[1];

用户@somethinghere很接近,OP选择了一个不适用于问题标题的答案,所以对于那些正在寻找问题标题答案的人,你可以在这里找到:

var r = document.querySelectorAll('input[type="radio"]');
if (r.item.length > 0) {console.log(r.item(1));
相关文章: