简体   繁体   中英

Checkbox: checkbox select all and unselect not effect on all

I'm trying to do a button to check and uncheck all boxes using react.But for some reason, 'Select All' is only selecting three of them, while 'Unselect All' is only unselecting those three and selecting the rest two.

My code is as below:

<button type='button' className='btnSelectAll' onClick={this.selectAllOrNone}>Select All</button>

this.selectAllOrNone = () => {
            let events = document.getElementsByClassName('toDoList_checkbox')
            let btnSelectAll = document.getElementsByClassName('btnSelectAll')[0]
            console.log(events)

            for (let i = 0; i < events.length; i++) {
                if (btnSelectAll.innerHTML === 'Select All') {
                    events[i].checked = true
                    btnSelectAll.innerHTML = 'Unselect All'
                }
                else if (btnSelectAll.innerHTML === 'Unselect All') {
                    events[i].checked = false
                    btnSelectAll.innerHTML = 'Select All'
                }

                console.log('btnSelectAll')
            }
        }

Anyone can suggest what the problem is?enter image description here

在此处输入图片说明 在此处输入图片说明

You're changing the buttons text on each iteration of your for loop, change the text after completing the for loop, since you change the button's text on each iteration, half will evaluate as false:

for (let i = 0; i < events.length; i++) {
    if (btnSelectAll.innerHTML === 'Select All') {
         events[i].checked = true;
    }else
    //else if (btnSelectAll.innerHTML === 'Unselect All') { //Don't need else-if
         events[i].checked = false;
    }
    
}

//Change your button text after the for loop completes
if(btnSelectAll.innerHTML === 'Select All'){
   btnSelectAll.innerHTML = 'Unselect All';
}else{
   btnSelectAll.innerHTML = 'Select All';
}

You are changing the button state inside the if in the loop. This means you are checking each item differently. Try to change the "select all" button state outside the loop, just after change every items.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM