我试图在提交之前获取单击时的单选输入值,以将其存储并显示在表单末尾的摘要中。我无法直接向输入添加单击功能,因此我循环输入并添加单击事件。现在,我只需要获取单击输入的值。这是代码:
var radios = document.getElementsByName('fields');
for (var i = 0, length = radios.length; i < length; i++)
{
radios[i].addEventListener("click", getValue);
}
function getValue(){
console.log(radios.value);
}
我得到的响应未定义。
最佳答案
不要使用'click'
事件。即使没有点击
,输入的状态也可以更改(即:按 Tab 键和使用空格键等)
使用'change'
或'input'
事件
const el_radio_1 = document.querySelectorAll('[name="radio_1"]');
const fn_radio_1 = evt => {
console.log(evt.target.value)
};
el_radio_1.forEach(el => {
el.addEventListener('change', fn_radio_1)
});
<label>
<input type="radio" name="radio_1" value="a"> Test a
</label>
<label>
<input type="radio" name="radio_1" value="b" checked> Test b
</label>
如果您使用标准Function
,请使用this.value
:
function fn_radio_1(evt) {
console.log(this.value)
console.log(evt.type)
}
关于javascript - 使用 JavaScript 单击时获取单选输入的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56531878/