分配单选按钮的标签而不是值(Assign radio button's label instead of value)

考虑html中的以下单选按钮:

<tr>  
    <td> Lighting </td>
    <td> <label for="lighting1"> Off </label> 
        <input id = "lighting1" name="lighting" type="radio" value="0"> </td>
    <td> <label for="lighting2"> Low </label> 
        <input id = "lighting2" name="lighting" type="radio" value="1"> </td>
    <td> <label for="lighting3"> High </label> 
        <input id = "lighting3" name="lighting" type="radio" value="2"> </td>
</tr>  

我需要一个javascript语句,它会将单选按钮的标签分配给变量而不是其值,即'关','低'或'高'而不是'0','1'或'2'。 当单选按钮被选中时。

这看起来很简单直接,但无论我尝试什么,我都无法实现它。 我还没有在论坛上找到任何工作答案。 请允许我说明所有不可行的试验,并仅使用一行代码就能启发我。


Consider the following radio buttons in html:

<tr>  
    <td> Lighting </td>
    <td> <label for="lighting1"> Off </label> 
        <input id = "lighting1" name="lighting" type="radio" value="0"> </td>
    <td> <label for="lighting2"> Low </label> 
        <input id = "lighting2" name="lighting" type="radio" value="1"> </td>
    <td> <label for="lighting3"> High </label> 
        <input id = "lighting3" name="lighting" type="radio" value="2"> </td>
</tr>  

I need a javascript statement that will assign the radio button's label on a variable instead of its value, ie 'Off', 'Low' or 'High' instead of '0', '1' or '2'. when the radio button is checked.

It seems so simple and straightforward yet I fail to achieve it no matter what I try. I haven't found any working answers on the forum either. Please spare me of stating all non workable trials and enlighten me with just a single line of code that works.

2022-05-10 21:05

满意答案

您可以使用通用名称获取收音机,并使用input.value = newValue更新值

function updateValues(){
  var radios = document.querySelectorAll('[name="lighting"]');
  for(var i = 0; i< radios.length; i++){
    var id = radios[i].getAttribute('id');
    radios[i].value = document.querySelector('label[for="'+id+'"]').textContent.trim()
  }
}

function registerEvents(){
  var radios = document.querySelectorAll('[name="lighting"]');
  for(var i = 0; i< radios.length; i++)
    radios[i].addEventListener("change", handleChange)
}

function handleChange(){
  console.log(this.value)
}

registerEvents();
<tr>
  <td> Lighting </td>
  <td> <label for="lighting1"> Off </label>
    <input id="lighting1" name="lighting" type="radio" value="0"> </td>
  <td> <label for="lighting2"> Low </label>
    <input id="lighting2" name="lighting" type="radio" value="1"> </td>
  <td> <label for="lighting3"> High </label>
    <input id="lighting3" name="lighting" type="radio" value="2"> </td>
</tr>

<p id="selectedValues"></p>

<button onclick="updateValues()" >Update Values</button>


You can fetch radios using common name and update values using input.value = newValue

function updateValues(){
  var radios = document.querySelectorAll('[name="lighting"]');
  for(var i = 0; i< radios.length; i++){
    var id = radios[i].getAttribute('id');
    radios[i].value = document.querySelector('label[for="'+id+'"]').textContent.trim()
  }
}

function registerEvents(){
  var radios = document.querySelectorAll('[name="lighting"]');
  for(var i = 0; i< radios.length; i++)
    radios[i].addEventListener("change", handleChange)
}

function handleChange(){
  console.log(this.value)
}

registerEvents();
<tr>
  <td> Lighting </td>
  <td> <label for="lighting1"> Off </label>
    <input id="lighting1" name="lighting" type="radio" value="0"> </td>
  <td> <label for="lighting2"> Low </label>
    <input id="lighting2" name="lighting" type="radio" value="1"> </td>
  <td> <label for="lighting3"> High </label>
    <input id="lighting3" name="lighting" type="radio" value="2"> </td>
</tr>

<p id="selectedValues"></p>

<button onclick="updateValues()" >Update Values</button>

相关问答

更多

使用单选按钮的HTML“标签”标签(Using the HTML 'label' tag with radio buttons)

标签标签是否与单选按钮配合使用? 是 如果是这样,你如何使用它? 与任何其他表单控件一样。 您可以给它一个与控件的id相匹配的属性,或者将控件放入标签元素中。 我想为左栏中的每个标签使用标签标签 标签是用于控制的,而不是一组控件。 如果要为一组控件添加标题,请使用带有<legend>的<fieldset> <legend> (并将<label>赋予集合中的每个控件)。 <fieldset> <legend> Salutation </legend> <label> <input type=...

检查单选按钮的标签的CSS选择器(CSS selector for a checked radio button's label)

input[type="radio"]:checked+label{ font-weight: bold; } //a label that immediately follows an input of type radio that is checked 对于以下标记工作非常好: <input id="rad1" type="radio" name="rad"><label for="rad1">Radio 1</label> <input id="rad2" type="radio"...

在单选按钮上使用“标签”(Using “label for” on radio buttons)

你几乎得到了 应该是这样的: <input type="radio" name="group1" id="r1" value="1" /><label for="r1"> button one</label> value中的值应该是要标注的元素的id。 You almost got it. It should be this: <input type="radio" name="group1" id="r1" value="1" /> <label for="r1"> button one</...

单选按钮标签样式(Radio Button Label styling)

首先,您需要更正标签代码,您有<label"Duration"> ,它应该有“for”,如下所示: <label for="Duration"> (请阅读: http : //www.w3schools.com/tags/tag_label.asp ) 然后你需要用你的CSS来定位<label> 。 在你的CSS定义中试试这个: label { text-size: 11px; font-weight: bold; } First you need to correct the l...

无法将单选按钮与标签分开(Not able to separate radio button from label)

使用<laber for="..">更容易,并删除position: absolute; https://www.w3schools.com/tags/att_label_for.asp #option { margin-left: 10px!important; } #wrapper { width: 100%; height: auto; display: flex; align-items: center; justify-content: cen...

获取单选按钮和标签文本的值放入两个TextField(Getting Value Of Radio Button And Label Text Put Into Two TextField)

标签上不会发生更改。 您需要使用无线电的更改。 $('input[name="20"]').on('change', function() { $('input[class="20"]').val($(this).val()); $('input[class="1_20"]').val($(this).parent().text()); }); The change doesn't occur on the label. You need to u...

单选按钮标签定位(Radio Button Label Positioning)

更新的小提琴代码: http://jsfiddle.net/mK3DV/10/ 归功于rickyduck Updated fiddle code: http://jsfiddle.net/mK3DV/10/ Credit goes to rickyduck

分配单选按钮的标签而不是值(Assign radio button's label instead of value)

您可以使用通用名称获取收音机,并使用input.value = newValue更新值 function updateValues(){ var radios = document.querySelectorAll('[name="lighting"]'); for(var i = 0; i< radios.length; i++){ var id = radios[i].getAttribute('id'); radios[i].value = document....

标签文本重叠单选按钮(Label text overlapping radio button)

尝试给出空白:nowrap; 通过短信避免文本拆分 Try giving whitespace:nowrap; to avoid the text split up ,for that span by Text Message

标签中间的单选按钮显示(radio button display in middle of label)

你可以试试这个: <label class="radio-label"> <input type="radio" name={{group}} checked={{value}} value={{name}}> <div>{{caption}}</div> </label> 和这样的造型...... .radio-label { width: 200px; // you can modify this as per your needs... } .radio-label,...

相关文章

更多

jquery1.4.4的radio选中项

var updkbval=$(&quot;input[name=sex][@checked]&quot ...

ios label 竖排设置

labelObject.numberOfLines = 0;labelObject.lineBreak ...

用‘button’跟‘text’组合代替‘file’,选择文件后点‘submit’,‘file’的值被清空

各位大虾晚上好,我有个问题想请教你们,我想美化html的file外观,但貌似现在还不能用css直接设计 ...

struts2 <s:checkbox>传值问题

action 中有个PageBean pageBean对象, pageBean中有属性List da ...

Just Forget To Ask The Handbag's Name

Bottega Veneta ogłoszenie Fire continues Daleko ali ...

Scaling Pinterest - From 0 To 10s Of Billions Of Page Views A Month In Two Years

这篇文件写的非常好,推荐大家重温一下: http://highscalability.com/blog ...

HMTL 表单标签

form表单标签: 要提交的内容,使用该标签包裹 action属性: 决定表单提交到哪里 ...

《Sundy's 《Android深入浅出》《Android高级应用》《Android开发视频教程》》[MP4]

中文名: Sundy's 《Android深入浅出》《Android高级应用》《Android开发视频 ...

She’s Not Carrying A Handbag

Gao Yuanyuan from after 2005 drama &quot; world fir ...

Storm,yahoo!S4比较

hadoop变得越来越热门,但是hadoop的设计是用来处理静态数据和批处理任务,流处理实施起来不是很 ...

最新问答

更多

Python / IPython奇怪的不可重现列表索引超出范围错误(Python/IPython strange non reproducible list index out of range error)

你得到IndexError的原因是你的输入文件显然不是完全用制表符分隔的。 这就是为什么当您尝试访问它时, splits[1]没有任何内容。 您的代码可以使用一些重构。 首先,你正在重复使用if -checks,这是不必要的。 这只是将cds0到7个字符,这可能不是你想要的。 我将以下内容放在一起,以演示如何重构您的代码,使其变得更加pythonic和干燥。 我无法保证它能够与您的数据集一起使用,但我希望它可以帮助您了解如何以不同的方式执行操作。 to_sort = [] # W

故事板从表格单元中延伸出来并显示其详细信息披露按钮(storyboard segue from a tablecell an its Detail Disclosure Button)

我不认为你可以链接一个特定的细节披露按钮瓦特/赛格。 我的故事板是非常程序化的B / C我使用了很多定制CGRect等。 所以我倾向于使用这样的东西: -(void)tableView:(UITableView *)tableView accessoryButtonTappedForRowWithIndexPath:(NSIndexPath *)indexPath { [self performSegueWithIdentifier:@"ViewControllerIdentifer"

我们可以将Gherkin功能文件与testcomplete集成(Can we integrate Gherkin feature files with testcomplete)

TestComplete不支持Gherkin功能文件。 但是,TestComplete具有SDK,因此可以自己为此创建扩展。 TestComplete does not support Gherkin feature files. However, TestComplete has SDK so it is possible to create an extension for this by yourself.

TrustAllCertificatesCallback被忽略(TrustAllCertificatesCallback is ignored)

我没有做过这样的事情,但看看我认为可以看出错误的例子。 试试这个代码: static class Program { static void Main() { var tcpclient = new TcpClient("remote.example.com", 443); var tcpstream = tcpclient.GetStream(); var sslstream = new SslStream(tcpstream,

返回嵌套元素的索引(Return index of nested element)

您需要获取父li元素的索引。 否则,您将获得列表项内锚点的索引,该索引始终为零。 $(this.parentNode).index(); You need to get the index of the parent li element. Otherwise you are getting the index of the anchor inside the list item, which will always be zero. $(this.parentNode).index();

在数组中重新编号元素的有效方法(Efficient way of re-numbering elements in an array)

您需要多次迭代列表,我认为没有办法解决这个问题。 毕竟,在开始更改元素(第二遍)之前,首先必须确定不同元素的数量(第一遍)。 但是请注意,由于对index的重复调用而not in列表中具有O(n),因此可能具有最多O(n ^ 2)的不同元素的数量。 或者,您可以使用dict而不是value_map的list 。 字典比列表具有更快的查找速度,因此,复杂性应该确实在O(n)的数量级上。 您可以使用(1)字典理解来确定旧值到新值的映射,以及(2)用于创建更新子项的列表理解。 value_map =

Express app定义的`static`文件夹无法正常工作(Express app defined `static` folder not working properly)

选项1 你可以改变这一行: app.use( express.static(__dirname + '/puplic')); //my public folder. 至 app.use('/oneTime', express.static(__dirname + '/puplic')); //my public folder 选项2 我假设你在公共文件夹中有一个js文件夹,然后你需要更改你的HTML代码:

使用node.js和socket.io每秒广播一次(Using node.js and socket.io to broadcast every second)

对于计时器值,请在服务器端本身每秒更新本地计时器。 每当有任何用户进来时,给他这个值以及计时器的总值。 然后客户端将根据dandavis评论在本地启动自己的计时器,但在服务器端保留一些间隔,如15或10秒,服务器将广播当前计时器值,以便客户端相应地进行同步。 简而言之,服务器将每隔10(n:你决定)秒后广播,但它将在本地每秒更新定时器变量。 每当客户端进入时,它将获得总计时器值和当前计时器值。 广播当前出价的休息功能可以以正常方式完成。 For timer value, keep updatin

如何让XMLSerializer将命名空间添加到嵌套对象中的属性?(How do I get the XMLSerializer to add namespaces to attributes in nested objects?)

IXmlSerializable也许? 注意我还添加了(对A ): [XmlElement("A", Namespace = "http://www.example.com/namespace")] public TestSoapHeaderTypeValuePair A {...} 代码如下: public class TestSoapHeaderTypeValuePair : IXmlSerializable { private string _type; private