我有单选按钮,我需要将选定的单选按钮更改为true,将其他更改为false
changeHandler (index, event) {
this.array[index].checked = true;
}
我具有以下数组结构:
[
{checked: false, title: 'first'},
{checked: false, title: 'second'},
{checked: false, title: 'third'}
]
当我选择收音机“ first”时,我需要将此obj值更改为true,将其他obj值更改为false,依此类推。
答案 0 :(得分:0)
您可以将所有checked
个成员设置为false,但将其成员具有选定的索引:
changeHandler (index, event) {
this.array.forEach((elem, idx) => elem.checked = idx == index);
}
答案 1 :(得分:0)
您可以按标题找到所有输入,并添加一个事件侦听器。
这是我的实现方式
// after document load
const myRadioButtons = [
{checked: false, title: 'first'},
{checked: false, title: 'second'},
{checked: false, title: 'third'}
];
myRadioButtons.forEach(radio => {
function updateRadioValue(id, value) {
document.querySelector(`#${id}`).checked = value;
myRadioButtons.find(item => item.title === id).checked = value;
}
function checkRadioAndResetOthers() {
myRadioButtons
.filter(item => item.title !== radio.title)
.forEach(item => updateRadioValue(item.title, false));
radio.checked = true;
console.log(myRadioButtons);
}
document
.querySelector(`#${radio.title}`)
.addEventListener('change', checkRadioAndResetOthers);
})
<input type="radio" id="first"/> First
<input type="radio" id="second"/> Second
<input type="radio" id="third"/> Third
答案 2 :(得分:0)
const array = [
{checked: false, title: 'first'},
{checked: false, title: 'second'},
{checked: false, title: 'third'}
];
function changeHandler(index) {
array.forEach((item, i) => item.checked = index === i);
}
changeHandler(0)
console.log(array);
changeHandler(1)
console.log(array);
changeHandler(2)
console.log(array);