Help - Search - Members - Calendar
Full Version: Swapping Values In Javascript
Darkside_RG > Technical Discussions > Guides/How To > Coding Guides
Mazuki
I was looking for a solution around the web for a quick and dirty hack for swapping a value of say a checkbox, well the only guide i found was very disheartening.

Here is how their guide went.

CODE
var chkbox = document.getElementById("mycheckbox");
if(chkbox.value == 1){chkbox.value = 0;}
else if(chkbox.value == 0){chkbox.value = 1;}


now i don't want to get into the fact that a checkbox can only be 1 or 0 so an else if is not even necessary, but i already did a022.gif

here's the optimized solution for swapping a 0/1 value or true/false in javascript

CODE
var chkbox = document.getElementById("mycheckbox");
chkbox.value ^= 1;


simple, and more importantly efficient :)

what this does is take the value of the checkbox and XORs it by 1, that's exclusive OR, meaning 1 or the other, but not both

so if the value is 1 a XOR of 1 means they are both the same, so it evaluates to 0 aka false
if the value is 0 a XOR of 1 means they are both different, so it evaluates to 1 aka true

and there you have it, swapping checkbox values without any ifs ands, or elses


now in my work i never got the chance to use this little snippet so i thought i'd share it for any javascripters out there that might need it sometime

enjoy
fonsov
Thanks Mazuki. This will come in handy.
Flatline
Thanks maz. A mind of useful information
Zeb
Thanks - recently started to learn Javascript and this could come in quite handy. Before I'd have gotten it down using a ternary but this is even better.
FlemGrem
You are far too clever for your own boots.
cheers for that, I'll use it and pretend its all mine, muhahaha
(now for explaining it :-S )
clapping.gif
drinks.gif

[EDIT]

would this work as well?

CODE
var chkbox = document.getElementById("mycheckbox");
chkbox.checked = !(chkbox.checked);
Mazuki
technically yes, since in boolean terms 0 = false and any other number = true in javascript

but the downside is the NOT operator i think you are trying to use is actually ~ in javascript and will simply flip the bits or XOR by 0xFFFFFFFF rather, whereas the XOR by itself will always flip it from 1 to 0 and back instead of 1 -> -1 and back

i tried it in a simple script and it came out reporting as -1 when using in a string, but you could try assigning -1 to the box and see what happens
This is a "lo-fi" version of our main content. To view the full version with more information, formatting and images, please click here.
Invision Power Board © 2001-2012 Invision Power Services, Inc.