javascript - 使用其 ID 复制 radio 值以使用 JavaScript 将其作为值插入到输入中

标签 javascript html input

我有一些 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/

相关文章:

javascript - 使用 EJS 输入值无法正确显示

javascript - Angular 选择选项

javascript - 使用 jQuery 的选项卡不透明度

java - 存储和检索数据的成本

C++ : recognizing lower case as correct when its stored as upper case?

php - 如何使用 node.js 实现 websocket 服务器?

javascript - Web 浏览器在尝试创建 blob 时发出错误 TypeError : Failed to construct 'Blob' : The provided value cannot be converted to a sequence

javascript - 动态表单框

javascript - fullpage.js - 如果 'scrolloverflow' 设置为 true 则无法向下滚动到下一部分

html - CSS 表单/输入操作