在javascript中选择相同名称的单选按钮

时间:2016-06-12 13:25:53

标签: javascript

我需要在JavaScript中的一个变量中添加2个无线电输入。以下代码仅识别第一个输入document.forms["myForm"]["satisfied"][0]onclick应由单选按钮选择触发。我可以将代码复制到2个变量和2个onclick事件中,但这并不理想。任何想法将不胜感激!

请注意,由于我的项目中对html的访问权限限制,我不能在我的情况下使用getElemntbyId或getElementbyTagName,因此我只能通过name标记触发。

var inputs = document.forms["myForm"]["satisfied"][0] || document.forms["myForm"]["satisfied"][1];

inputs.onclick = function() {
    document.forms["myForm"]["check"].disabled= false;
}

2 个答案:

答案 0 :(得分:1)

使用document.querySelectorAll()选择attribute-value selector的元素。

var radios = document.querySelectorAll('input[name="satisfied]');

// Iterate over them and bind event
for (var i = 0, len = radios.length; i < len; i++) {
    radios[i].addEventListener('change', function() {
        document.querySelector('input[name="check"]').disabled = false;
    }, false);
}

Demo

答案 1 :(得分:1)

我建议:

// retrieving all elements with the name of 'satisfied':
var inputs = document.getElementsByName('satisfied');

// defining a function so that multiple elements can
// be assigned the same function:
function enable () {

    // iterating over the inputs collection:
    for (var i = 0, len = inputs.length; i<len; i++) {
        // updating the 'disabled' property to false,
        // thus enabling the inputs:
        inputs[i].disabled = false;
    }
}

// iterating over the inputs collection:
for (var i = 0, len = inputs.length; i<len; i++) {
    // binding the enable() function as the
    // event-handler for the click event:
    inputs[i].addEventListener('click', enable);
}

上面的第一个选项是相当原始的;为当代浏览器更新了以下内容:

function enable() {
    // using Array.from() to convert the collection returned by
    // document.getElementsByName() into an array; over which we
    // iterate using Array.prototype.forEach().

    // 'this' is supplied from EventTarget.addEventListener();
    // and allows us to retrieve the name, and the associated
    // 'group' of elements for the specific input; meaning this
    // same function can be bound to multiple 'groups' of elements
    // without interfering with the other 'groups':
    Array.from( document.getElementsByName( this.name ).forEach(function (el) {
        // el: the current element in the Array over which
        // we're iterating.

        // updating the 'disabled' property to false:
        el.disabled = false;
    });
}

// as above, except we supply the 'name' explicitly:
Array.from( document.getElementsByName('satisfied') ).forEach(function (el) {
    // binding the enable() function as the event-handler
    // for the click event:
    el.addEventListener('click', enable);
});