表单my_form
带有一组带有name=my_radio
的单选按钮,我可以使用my_form.elements.my_radio
获得RadioNodeList
个对象。我可以使用该对象的value
属性获取当前所选按钮的值,如果我将字符串分配给value
属性,则所选选项会根据需要进行更改。
我希望能够my_form.elements.my_radio.addEventListener('change', ...
来监听价值变化(通过用户选择不同的选项),但它没有这样的方法。
如何检测值的变化?
是在每个单独的单选按钮对象上设置事件侦听器的唯一方法吗?
var my_form = document.querySelector('#my_form');
var my_radio = my_form.elements.my_radio;
// This fails since RadioNodeList has no addEventListener function
/*
my_radio.addEventListener('change', function () {
console.log("Value changed; new value is " + my_radio.value);
});
*/
// The following works, but is there a better way, such as with a single event listener?
for (var i = 0, l = my_radio.length; i < l; i++) {
my_radio[i].addEventListener('change', function () {
console.log("Value changed; new value is " + my_radio.value);
});
}
<form id=my_form>
<div>
<label>
<input type=radio name=my_radio value=value_1>
Value 1
</label>
</div>
<div>
<label>
<input type=radio name=my_radio value=value_2>
Value 2
</label>
</div>
<div>
<label>
<input type=radio name=my_radio value=value_3>
Value 3
</label>
</div>
<div>
<label>
Some other field where I don't need to detect changes
<input name=some_other_field>
</label>
</div>
</form>
答案 0 :(得分:0)
你可以试试这个:
my_form.addEventListener('change', function () {
console.log("Value changed; new value is " + my_radio.value);
});
答案 1 :(得分:0)
document.formName.radioButtons [thisOne] .click()