【问题标题】:How to get radio button value inside a label?如何获取标签内的单选按钮值?
【发布时间】:2019-04-09 23:04:16
【问题描述】:

这里的新手,我想知道为什么我无法获取标签内单选按钮的值?

function myButtonTrigger(c) {
  if (c.value == "1") {
    document.getElementById("id1").style.display = "table-row";
    document.getElementById("id2").style.display = "none";
  } else if (c.value == "2") {
    document.getElementById("id1").style.display = "none";
    document.getElementById("id2").style.display = "table-row";
  } else {}
}
table {
  border-collapse: collapse;
}

table, th, td {
  border: 1px solid black;
  background-color: #39739D;
  color: white;
}
This is my Button

<div class="btn-group" data-toggle="buttons">
  <label class="btn btn-default">
            <input value="1" type="radio" name="choices" onClick="myButtonTrigger(this)"></input>Dental
			        </label>
  <label class="btn btn-default">
           <input value="2" type="radio" name="choices" onClick="myButtonTrigger(this)"></input>Rehab
		           </label> </div>

This is the data to be hidden.<br><br>

<table>
  <tr id="id1">
    <td id="id1">Dental Data</td>
    <td id="id1">Specialization Data1</td>
    <td id="id1">Schedule Data</td>
    <td id="id1">Room Data</td>
  </tr>
  <tr id="id2">
    <td id="id2">Rehab Data</td>
    <td id="id2">Specialization Data2</td>
    <td id="id2">Schedule Data</td>
    <td id="id2">Room Data</td>
  </tr>
</table>

【问题讨论】:

  • 您的 HTML 无效。 id 必须是唯一的
  • @Quentin 我们有办法获取标签内单选按钮的值吗?
  • 正如我所说,我无法重现该问题。所以是的,你已经这样做了。
  • 嗨,我已经上传了整个代码,请看下面。

标签: html radio-button label


【解决方案1】:

只需使用 .checked 属性

var radioButtons = document.getElementsByName("choices");

function myButtonTrigger() {
  if(radioButtons[0].checked) {
    // first radio button checked
  } else if(radioButtons[1].checked) {
    // second radio button checked
  }
}

或者您可以使用查询选择器按值获取元素:

if(document.querySelector("input[name='choices'][value='1']").checked)

编辑:不要在两个或多个元素上使用相同的 id,你只能在标签上使用它,它会起作用。 ID意味着身份,唯一。一些不错的选择:

document.getElementsByClassName("class1");
document.querySelectorAll("#id1, #id2, #id3, #id10000, #anotherId");
document.querySelectorAll("table tr#id1 td"); // marks every td in tr with id id1 in table (really, tr and td in table, wow)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-17
    • 1970-01-01
    • 2017-09-27
    • 2021-09-26
    • 2019-11-13
    • 2015-06-26
    相关资源
    最近更新 更多