我有一些 HTML 代码如下:
<input name="bid" type="radio" value="1" id="1234"/>
<input name="bid" type="radio" value="2" id="5678"/>
<input type="text" id="paymount" name="paymount" value=""/>
期望的功能:
选中radio=1
时,paymount
字段值将显示为1234
。选中 radio=2
后,paymount
字段值将显示为 5678
。
我在 Stack Overflow 上找到了帖子,但其中很多都与隐藏文本字段有关。
最佳答案
使用 change 事件处理器来监听事件。
// use `[].slice.call(document.querySelectorAll('[name="bid"]'))
// for older browser to covert NodeList to Array
// although check polyfill option of `ArrayforEach` for older browser
// or use simple `for` or `while` loop for iterating
// get all radio with the name,covert NodeList to array and iterate
Array.from(document.querySelectorAll('[name="bid"]')).forEach(function(ele) {
// add event handler to the element
ele.addEventListener('change', function() {
// update value of the input element
document.getElementById('paymount').value = this.id;
// if you are used `data-id="value" attribute instead of `id`
// then get the value using `this.dataset.id`
});
});
<input name="bid" type="radio" value="1" id="1234" />
<input name="bid" type="radio" value="2" id="5678" />
<input type="text" id="paymount" name="paymount" value="" />
仅供引用:使用自定义 data-*
attribute id
属性用于存储对应的值,目的是为了唯一标识一个元素。定制data-*
attribute可以从 dataset
中检索值元素的属性。
关于javascript - 使用其 ID 复制 radio 值以使用 JavaScript 将其作为值插入到输入中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39074645/