2016-06-12 26 views
1

我需要在JavaScript中將2個無線電輸入添加到一個變量中。以下代碼僅識別第一個輸入爲document.forms["myForm"]["satisfied"][0]onclick應通過單選按鈕選擇觸發。我可以將代碼複製到2個變量和2個onclick事件中,但這並不理想。任何想法將不勝感激!在javascript中選擇同名單選按鈕

請注意,由於在我的項目中訪問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; 
} 

回答

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

+0

謝謝,我測試你的代碼,但它似乎沒有觸發點擊單選按鈕:https://jsfiddle.net/wpLuenLv/3/ – Nima

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); 
}); 
+0

謝謝你的描述性答案。我嘗試了第二個選項,但沒有得到結果,你可以在這裏看到:https://jsfiddle.net/wpLuenLv/ 每次單擊單選按鈕時,都應該啓用複選框。 – Nima