Swe*_*ong 12 html javascript 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=""/>
Run Code Online (Sandbox Code Playgroud)
所需功能:
当radio=1被选中时,paymount字段值将显示为1234.当radio=2被选中时,paymount字段值将显示为5678.
我在Stack Overflow上发现了帖子,但其中很多都与隐藏文本字段有关.
Pra*_*lan 19
使用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`
});
});Run Code Online (Sandbox Code Playgroud)
<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="" />Run Code Online (Sandbox Code Playgroud)
仅供参考:使用自定义data-*属性存储属性的相应值目的id是用于唯一标识元素. 可以从元素的属性中检索自定义 data-*属性值dataset.
<form name="radioForm">
<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=""/>
</form>
<script type="text/javascript">
var radio = document.radioForm.bid,
input = document.getElementById('paymount');
for(var i = 0; i < radio.length; i++) {
radio[i].onclick = function() {
input.value = this.id;
};
}
</script>
Run Code Online (Sandbox Code Playgroud)
我不确定这是否是最好的解决方案,但以下是您需要的工作.
var inputs = document.querySelectorAll('input[name="bid"]'),
paymount = document.getElementById('paymount');
// loop over element, and add event listener
for (var i = 0; i < inputs.length; i++) {
inputs[i].addEventListener("change", onChange);
}
// callback
function onChange(){
paymount.value = this.id; // change paymount value to the selected radio id
}Run Code Online (Sandbox Code Playgroud)
<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=""/>Run Code Online (Sandbox Code Playgroud)