2016-08-25 47 views
1

使用表格my_form帶有一組單選按鈕name=my_radio我可以通過my_form.elements.my_radio得到一個RadioNodeList對象。我可以通過該對象的value屬性獲取當前所選按鈕的值,如果將字符串分配給value屬性,則所選選項會根​​據情況進行更改。如何檢測RadioNodeList的值的變化?

我希望能夠做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() { 
 
\t console.log("Value changed; new value is " + my_radio.value); 
 
}); 
 
}
<form id=my_form> 
 
<div> 
 
\t <label> 
 
\t \t <input type=radio name=my_radio value=value_1> 
 
\t \t Value 1 
 
\t </label> 
 
</div> 
 
<div> 
 
\t <label> 
 
\t \t <input type=radio name=my_radio value=value_2> 
 
\t \t Value 2 
 
\t </label> 
 
</div> 
 
<div> 
 
\t <label> 
 
\t \t <input type=radio name=my_radio value=value_3> 
 
\t \t Value 3 
 
\t </label> 
 
</div> 
 
<div> 
 
\t <label> 
 
\t \t Some other field where I don't need to detect changes 
 
\t \t <input name=some_other_field> 
 
\t </label> 
 
</div> 
 
</form>

+0

這還是建立在'my_form'事件偵聽器;節點可以得到EventListeners,NodeLists不能 – Hamms

+0

'my_form'上的監聽器必須檢查被更改的元素是否是單選按鈕中的一個,特別是,對嗎?因爲它也會被調用來更改其他元素嗎? – tremby

+1

請在您的問題中包含示例HTML(和JavaScript)。換句話說,請包括[mcve]。這樣做可以幫助大家談論同樣的事情。它還減少了人們爲解答您的問題所做的工作。這使得你更有可能A)獲得答案,B)答案實際上解決了*你的問題。更不用說調試問題需要[mcve],這就是主題。 – Makyen

回答

0

你可以試試這個:

my_form.addEventListener('change', function() { 
console.log("Value changed; new value is " + my_radio.value); 
}); 
+0

當窗體中的任何其他輸入發生更改時會觸發,例如我的示例中的some_other_field。 – tremby