Invert Selection of checkboxes or radio buttons in an HTML form
Uses jQuery & JavaScript to select the opposite of any checkboxes that are currently selected
This uses PHP, but you can simply view page source
to get a pure HTML version
Invert Current Selection
(checkboxes only)Select All
Select None
Select None
works to deselect radio buttons
This is for mutually exclusive choices, but when the entire is question optional & you want no response
to be valid
The other 2 functions can be used on radio buttons, but aren’t effective since radio buttons are mutually exclusive.
Results in the last radio button being selected
It doesn’t break anything, just doesn’t work as intended
No CSS just to make things easier to understand
Possible improvements could be styling the buttons
name
attribute of an HTML input tagname
for a group of elementsname
attribute of each checkbox in a group must have square brackets []
at the end<input type='checkbox' id='chk1' name='chkBoxes[]' value='1'>
<input type='checkbox' id='chk2' name='chkBoxes[]' value='2'>
[]
in name='chkBoxes[]'
$_POST
array when the form is submitted, instead of individual checkboxes. (For easier processing)[]
, just group them by having the same exact name
attribute for a grouponClick
event handler must be placed on the page near the checkboxes with the correct argument in the function call<input type="button" name="btnInvert" onclick="invert('chkBoxes[]')" value="Invert">
invert()
function when clickedchkBoxes[]
invert()
the checkboxes in the group chkBoxes[]
selectAll()
and selectNone()
is the name of the function to callitem.prop("checked", true);
because item.attr('checked','checked');
doesn’t workattr
updates the HTML & you can see it happen in realtime using Inspect Element, but the actual page doesn’t changeselectAll
simply adds element.prop("checked", true);
to every element in a group regardless of its current statetrue
if it’s already true
selectNone
is the opposite & simply sets the property
to false
invert
function checks if an input is checked (true/false) & sets the new property to the opposite of its previous state by negating true
or false
selectNone
ON RADIO BUTTONS TO “DE-SELECT” THE RADIO BUTTON ALTOGETHER, BUT invert
& selectNone
WON’T WORK FOR RADIO BUTTONS*$_POST
array (empty to start with since form isn’t submitted)for loop
to print checkboxes & labels (or just use the HTML version)The attempts/
folder is a collections of my initial versions which didn’t pan out
I cobbled together my own invert()
function based on various sources because none of them individually was exactly what I was looking for
checked
wasn’t actually updating the html