samedi 27 février 2021

Get "checked=true/false" value of checkbox from inside HTML attributes

I want to enable and disable checkboxes based on two variables: 1) Is there already a checked count of 2+, 2) Is the current checkbox enabled or disabled. i.e. I have a list of items, and I want to limit the user to only selecting two out of (potentially) endless options.

I have a handleCheck() function, but I think by the time that's applied it's already too late to control the checked value of the checkbox, right? Because I can successfully call alert() after the user has checked their third box, but then the check appears anyway; I can't stop it from being checked. That's why I'd like to put the control inside the HTML: the checkbox will be disabled if the count is more than two and the user hasn't chosen this checkbox. In order to choose this checkbox, they'd have to deselect another.

What I essentially want to do is this:

disabled={count >= 2 && thisCheckbox.checked === false}

I'm using React to dynamically render checkbox + a whole load of data and visuals on a case-by-case basis, so it's not like all the checkboxes are in one neat form.

I've tried various SO threads but most of them use jQuery or do their handling in JS in the onChange function (handleCheck(), in my case), which is already too late because the check will still be applied (as far as I know).




Aucun commentaire:

Enregistrer un commentaire