javascript - 如何获取选中的单选按钮的文本?

标签 javascript radio-button label radio-group

我有一组单选按钮,想要获取选中的单选按钮,然后提醒文本,而不仅仅是它的值。为了解释更多,当用户单击第一个单选按钮,然后提交表单时,我希望浏览器提醒“桌面案例”。我想在没有 jQuery 的情况下实现这一目标。

<form action="" name="form1">
    <label for="radio400">Desktop Case</label>
    <input type="radio" name="rad_case" value="400" id="radio400"/>

    <label for="radio401">Mini Tower</label>
    <input type="radio" name="rad_case" value="401" id="radio401"/>

    <label for="radio402">Full Tower</label>
    <input type="radio" name="rad_case" value="402" id="radio402"/>

    <input type="button" value="Submit" name="btn_submit" onclick="update_order_onclick()"/>
</form>

最佳答案

以下内容适用于您的示例。它使用 CSS 选择器来定位已检查的输入。根据其 id,找到适当的标签:

function update_order_onclick() {
  var value= 'Nothing selected',
      selected= document.querySelector('input[name="rad_case"]:checked'),
      selection= document.querySelector('#selection');
  
  if(selected) {
    value= document.querySelector('label[for="'+selected.id+'"]').innerHTML;
  }

  selection.innerHTML= value;
}
<form action="" name="form1">
    <label for="radio400">Desktop Case</label>
    <input type="radio" name="rad_case" value="400" id="radio400"/>
    <br>

    <label for="radio401">Mini Tower</label>
    <input type="radio" name="rad_case" value="401" id="radio401"/>
    <br>

    <label for="radio402">Full Tower</label>
    <input type="radio" name="rad_case" value="402" id="radio402"/>
    <br>

    <input type="button" value="Submit" name="btn_submit" onclick="update_order_onclick()"/>
</form>

<div id="selection"></div>

关于javascript - 如何获取选中的单选按钮的文本?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28125165/

相关文章:

R数据表: label the counts of consecutive non-NA values

cocoa - 在 cocoa 中选择后如何在标签上返回文件名?

javascript - 如何让 React.js 输出有效的 xml 而不是 html?

javascript - 选择框 onChange 事件

javascript - 根据下拉值显示内容的 knockout 问题

javascript - 在 IE 的 Html 中动态创建单选按钮

ios - 如何使用标签文本 (Int) 值编写 if 条件

javascript - 该函数是否有两种以上的可能结果?

c# - 生成具有不同 'Content' 的单选按钮

html - 用于转到 URL 的单选按钮