邪魔な JavaScript (onclick
属性)を使用しないソリューションを次に示します。
/*
* Convert to array so we can use `forEach()` and `every()`
*/
function toArray(any) {
return Array.prototype.slice.call(any);
}
var observed = toArray(document.querySelectorAll('[data-observe]'));
var listened = [];
var result = document.querySelector('#result');
/*
* Gather all elements we want to listen for change:
* observed elements and their siblings with the same name
*/
observed.forEach(function (target) {
var siblings = toArray(document.querySelectorAll('[name=' + target.name +']'));
listened = listened.concat(siblings);
});
listened.forEach(function (radio) {
radio.addEventListener('change', function () {
var checked = observed.every(function (item) {
return item.checked;
});
checked ?
result.removeAttribute('hidden') :
result.setAttribute('hidden', 'true');
});
});
デモ: http://jsfiddle.net/sZHAA/1/