Programming Puzzles & Code Golf Stack Exchange is a question and answer site for programming puzzle enthusiasts and code golfers. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

Write a program that creates a two-state checkbox that people can interact with using a mouse.

Specifically, your program should achieve all of the following:

  1. Have a 8×8 pixel (or larger if desired) region of the screen that is the clickable area of the checkbox. Henceforth this region is simply called the checkbox.

  2. When the mouse cursor is moved within the checkbox and the default* mouse button is pressed, the checkbox should toggle states.
    Checked becomes unchecked. Unchecked becomes checked.

  3. The checkbox should not move when it is toggled.

  4. In the checked state, the checkbox may be any colors.

  5. In the unchecked state, the checkbox may be any colors as long as at least 16 pixels are visually distinct from the checked state.

  6. In a single program instance, all checked states should be visually identical to one another and all unchecked states should be visually identical to one another.

  7. Don't end the program until it's explicitly terminated (e.g. via exit button or Alt+F4), so a user can click the checkbox as much as they want.

*You may assume the default mouse button is always left click, but it's also fine to use the default as defined by mouse software or the OS, which may not actually be left click depending on the user.

Notes

  • It does not matter what is outside of your checkbox region. It could just be the desktop. It could be a portion of a console that changes on every toggle.

  • It does not matter what state your checkbox starts in.

  • The checkbox region may have any dimensions at or above 8×8 pixels. It need not be square.

  • You may make minor allowances for settings that are out of your control such as console font size, browser zoom, monitor resolution, etc. As long your program works in a reasonable test setting it should be valid.

  • If your program opens a window, you may assume it has been dragged to an appropriate location on the screen if necessary (e.g. top left corner).

  • You may use markup languages such as HTML or other languages we usually don't consider as full-fledged programming languages.

  • Your checkbox must be be toggleable using the default mouse button. It's alright if it also toggles for other forms of input (e.g. right mouse button), with the exception of mouse motion. i.e. the state should not change if the mouse is merely moved within the checkbox.

  • Screenshots of your checkbox in action are highly encouraged!

Scoring

The shortest code in bytes wins.

Example

A canonical HTML example in 23 bytes.

<input type="checkbox">

For me in Google Chrome, this makes a 12×12 pixel checkbox and about 30 pixels clearly change between checked and unchecked states.

I make the allowance that browser zoom is at 100%.

share|improve this question
1  
Can the checkbox cover the entire screen? – Kritixi Lithos 2 days ago
    
@KritixiLithos Yes, that would be valid.Though note that you may, if desired, count a particular 8x8 region as the official checkbox, even if a larger region works. – Helka Homba 2 days ago
    
@Helka Homba - is it allowed for an app to display other controls, aside the checkbox itself ? – zeppelin 2 days ago
    
Is it OK for the checkbox to toggle on other sorts of input? (For example, is a solution correct if the checkbox toggles on any sort of user input, regardless of whether it's a mouse click, a mouse movement, or a keypress? It'd toggle on a mouse click, but it'd toggle on other stimuli too.) – ais523 2 days ago
1  
@zeppelin "It does not matter what is outside of your checkbox region. It could just be the desktop. It could be a portion of a console that changes on every toggle." So, as long as the checkbox is there, it doesn't matter what else is. – Helka Homba 2 days ago

43 Answers 43

Mathematica, 10 bytes

Checkbox[]

Assumes Mathematica's notebook environment.

The two states look like this:

enter image description here

share|improve this answer
55  
Sure. Mathematica cheats again. – Matthew Roh 2 days ago

Processing, 78 66 65 63 61 bytes

2 bytes saved thanks to @TuukkaX by using -a%2 instead of a%2*-1

2 bytes saved thanks to @TuukkaX by using a=-a

int a=1;void draw(){background(a);}void mousePressed(){a=-a;}

The checkbox alternates between being black and white.

Explanation

int a=1;                   //the variable that contains the state of the checkbox
void mousePressed(){a=-a;} //if the mouse is pressed, change the sign of a

Now there are many other alternatives like using an if-statement to process this, but then it gets weird and constantly changes the background while the mouse is being pressed. I first tried mouseButton, but then I would need more conditions and more code that will just end up much more verbose.

Now for mousePressed() to be called forever (otherwise it would just stop after the program has just started), we need a draw() function.

void draw(){               //loop infinitely
  background(a);           //set the sketch's background to -a%2
  //if a ==  1, the background colour is set to almost black
  //if a == -1, the background colour is set to white
}

enter image description here


A smaller checkbox would be 90 bytes (the checkbox is in the top left corner, so we can remove some mouse conditions):

int a=1;void draw(){fill(a);rect(0,0,8,8);}void mousePressed(){if(mouseX<9&mouseY<9)a=-1;}
share|improve this answer
1  
Clever use of how Processing accept single integers as grayscale colours! – FlipTack 2 days ago
    
@FlipTack It seems that white can also be expressed as fill(-1) – Kritixi Lithos 2 days ago
1  
I have an idea. Initialize a to 1 instead of 0. Change a++ to a=-a, which makes -a%2 just a. This will toggle a between 1 and -1. I don't know what color 1 produces though. – TuukkaX 2 days ago
    
@TuukkaX Yup it works. color(1) produces #010101 which is very close to black – Kritixi Lithos 2 days ago

Bash, 67 55 50 35 32 31 bytes

:()(read -p$[i^=1]
›?9h -sn6
:)

The code contains a CR byte (first newline) and a CSI byte (small right angle bracket with the Windows-1252 encoding). It requires xterm (or equivalent) and the ISO-8859-1 encoding (or similar).

The code defines a function named :, which alternately displays a white 1 or 0 in a black rectangle. There are exactly 24 differing pixels with xterm's default settings. (proof)

For an older version that toggles the color of the entire terminal, check revision 10 of this answer.

Thanks to @ais523 for suggesting xterm, which saves 4 bytes!

How it works

:(...) creates a function named : that executes ....

The read command does the actual magic.

  • -p specifies an input prompt, which is printed to STDOUT.

    • $[i^=1] is an arithmetic expansion which XORs the variable i with 1. i may initially be unset; when this occurs, it will be treated as 0.

    • The carriage return places the cursor back at the beginning of the line.

    • ›?9h captures the mouse in supported terminals. Each click will send six characters to the terminal, namely ←[Mbxy, where represents the ESC byte (0x1b). ←[ indicates an escape sequence, M the mouse, b the button (0x20 + the button number), x the x coordinate of the click (0x20 + coordinate), and y the y coordinate.

    • -sn6 makes read silent (the mouse input won't be echoed to STDERR) and stops after reading exactly 6 bytes. It saves the input in the REPLY variable, but we're not interested in the output it produces.

Finally, once read finishes (after exactly one mouse click), : recursively calls itself, entering an infinite loop.

Creation and invocation

$ echo $':()(read -p$[i^=1]\r\x9b?9h -sn6\n:);:' > checkbox.sh
$ xxd -c 17 -g 1 checkbox.sh
0000000: 3a 28 29 28 72 65 61 64 20 2d 70 24 5b 69 5e 3d 31  :()(read -p$[i^=1
0000011: 5d 0d 9b 3f 39 68 20 2d 73 6e 36 0a 3a 29 3b 3a 0a  ]..?9h -sn6.:);:.
$ LANG=en_US xterm -e bash checkbox.sh

Output

screencast

share|improve this answer
    
I was working on a similar solution to this myself (although in a different language, forcing me to give up because I couldn't find a way to take input without a newline). A likely improvement: change 1000h to 9h (the difference is that 1000h handles both mouse press and release, and 9h handles only mouse release). This might or might not need changes elsewhere in the code. – ais523 2 days ago
    
@ais523 I tried that, but at least my terminal emulator (Konsole) doesn't seem to support it. Do you know one that does? – Dennis 2 days ago
    
gnome-terminal seems to work, that's what I was using for testing (edit: but I don't think it supports a 1-byte CSI). xterm should also work and might be easier to install if you have a KDE system. (I just tested this myself; it works with \x1b[ but not with \x9b for some reason, possibly related to my stty settings rather than to the terminal itself.) – ais523 2 days ago
    
@ais523 I do have xterm. I'll check when I'm back at my PC. – Dennis 2 days ago
5  
I love how it becomes :) from :( by the end – Andras Deak yesterday

HTML, 20 bytes

Don't know how valid this will be as an answer. HTML requires the tag to be closed to legally validate, but modern browsers will automatically close them so it's executable.

<input type=checkbox

share|improve this answer
2  
I was looking at this as an option earlier (without quotes) but completely missed the closing >. +1 and valid IMHO. – ElPedro 2 days ago
1  
On this site, languages are defined by their implementation, so this seems fine to me. – John Gowers yesterday
    
Thanks @JohnGowers , I've been wondering about the definition of how much abuse is acceptable. – Jan yesterday

AHK, 25 bytes

Gui,Add,Checkbox
Gui,Show

Output -

Mouse pointer is not captured in this gif

share|improve this answer

Python REPL, 45 bytes

from tkinter import*
Checkbutton(Tk()).pack()
share|improve this answer

Tcl/Tk, 21 byte

Golfed

grid [checkbutton .c]

enter image description here

share|improve this answer

GeoGebra, 10 bytes

Checkbox[]

Entered into the input bar.

Here is a gif of the execution:

Program execution

share|improve this answer
1  
Whoah, GeoGebra. I remember that. It's been a while. – QPaysTaxes 2 days ago

Unix Shell (+x11-apps), 3 bytes

Disclaimer

The answer below is boring, borderline and "feels cheating" (at least to me).

Yet, it does not seem to violate any of the challenge rules "as written", or "default loopholes", so I'm posting it.

(If you can point a specific rule it breaks, please comment on !)

Golfed

xgc

The xgc program demonstrates various features of the X graphics primitives.

The xgc screen is actually filled with various checkboxes:

enter image description here

and "sticky buttons" (which qualify as checkboxes, under this challenge rules):

enter image description here

share|improve this answer
    
+1 for using a readable call/command. – KeyWeeUsr yesterday

HTML with JavaScript - 136 124 120 115 113 111 109 79 bytes

<p style=height:20;border:solid onClick=t=this;t.innerHTML=(t.e=!t.e)?'x':''>

-2 with thanks to @KritixiLithos

Reduced to 79 after some fantastic golfing from @Jan. Although the new version fits the requirements I have kept the old version for professional pride reasons.

While it is perfectly valid to use built-ins, I thought it was more fun to create my own from scratch. Tested with Chrome and Firefox. border:solid is there for IE compatibility but I don't know if it is actually needed in newer IE versions - I don't have IE available to test.

The px in the height is there for the benefit of "Run code snippet" so is not included in the "real" byte count. It works fine in the browser without it.

<p style=height:20px;border:solid onClick=t=this;t.innerHTML=(t.e=!t.e)?'x':''>

Previous version:

<p id=d style="width:20px;height:20px;border:solid 1px"onClick="d.innerHTML=d.innerHTML=='x'?'':'x'"align=center>

share|improve this answer
1  
Can you do id=d to remove d=this? – Kritixi Lithos 2 days ago
1  
@KritixiLithos - Indeed I can. Thanks and well spotted :) – ElPedro 2 days ago
1  
You don't need to set the width, the rules say it can be any dimensions. If you store the state on a property on this you'll save setting the id. If you store this in a property you'll save a few bytes. The align is unnecessary. Since there are no spaces in the attribute strings, you don't need the quotes. <p style=height:20px;border:solid onClick=t=this;t.innerHTML=(t.e=!t.e)?'x':''> 79 bytes – Jan 2 days ago
    
@Jan - Thanks! The width bit is my own professional pride. If I don't set it it looks ugly and since this answer is never going to win and was just posted as an alternative I'll probably leave it there. Other than that some great hints. Many thanks. Will update tomorrow. – ElPedro 2 days ago
    
Thanks @Easterly. Updated the code but forgot the other bits. It's getting late. – ElPedro 2 days ago

Html + javascript, 32 30 25 chars

<p onclick=innerHTML^=1>0

share|improve this answer
    
this is implicit and can be removed. Also, innerHTML is shorter. – Dennis yesterday
    
@Dennis, strange with this... Thank you. – Qwertiy yesterday

Octave, 36 20 bytes

uicontrol('sty','c')

Thanks to @LuisMendo saved 16 bytes!

share|improve this answer
1  
uicontrol('sty','c') also works – Luis Mendo 2 days ago
    
@LuisMendo Thanks! 1/2 byte counts saved! – rahnema1 2 days ago

Excel VBA, 38 32 Bytes

-6 Thanks to pajonk for replacing [A1],[A1],9,9 with 0,0,9,9

Immediates Window function that inserts a checkbox of height=9 and width=9, at the cell A1 on the first sheet of the active Excel VBA project

Sheets(1).CheckBoxes.Add 0,0,9,9
share|improve this answer
    
Seems that 1,1,9,9 as arguments works as well. – pajonk 2 days ago
1  
You dont need the Sheet(1)., you can run this quickly enough in Excel but CheckBoxes is inherint to the active sheet – Mr.Burns yesterday
    
@Mr.Burns I have checked into this, but without directly referencing any Worksheet object, the CheckBoxes.Add method throws an error stating "Object Required" – Taylor Scott yesterday
    
@TaylorScott You are correct, I put the code in a sheet module rather than a normal module .. My mistake xD – Mr.Burns 18 hours ago

Scratch, 2 blocks

enter image description here

Put this script in the default sprite (which comes with 2 costumes)

share|improve this answer
1  
Online demo: phosphorus.github.io/… – primo 18 hours ago

TI-Basic, 15 bytes

While 1:Shade(0,9:Input :ClrDraw:Input :End

Fairly straightforward. The checkbox covers approximately 40% of the screen and alternates between black and white. When checked, the screen will look something like this:

screen

share|improve this answer

C#, 124 bytes

checkbox checked and not checked note: because of edits, the picture doesn't exactly represent what the code makes, the "checkBox1" isn't displayed with the current code.

using System.Windows.Forms;class P{static void Main(){var a=new Form();a.Controls.Add(new CheckBox());Application.Run(a);}}

ungolfed:

using System.Windows.Forms;
class P{
  static void Main(){
    var a=new Form();
    a.Controls.Add(new CheckBox());
    Application.Run(a);
  }
}
share|improve this answer
    
If you didn't find anything about this on meta, ask about this on meta. – Matthew Roh yesterday
    
You can get rid of the spaces in var a = new Form();. – Qwerp-Derp yesterday
    
@Qwerp-Derp I removed them for counting, I just pasted the wrong thing, thanks. – satibel yesterday

VBA (Word), 74 57 bytes

-17 thanks to Taylor Scott

Sub a()
f = a.FormFields.Add(Selection.Range, 71)
End Sub

Filename of the document should be a.

share|improve this answer
1  
You can replace the wdFieldFormCheckBox with 71 (the integer value of the wdFieldFormCheckBox constant) for a savings of 17 bytes – Taylor Scott 2 days ago
    
I think you can remove the newlines for -2 bytes. – devRicher 2 days ago

KV Lang, 8 bytes

CheckBox

enter image description here


assuming a really basic Python environment for kv lang to even run:

from kivy.app import runTouchApp
from kivy.lang import Builder
runTouchApp(Builder.load_string('CheckBox'))

This works basically because CheckBox is a Kivy widget included in a kivy.Factory as each widget from the standard library.

That simple string creates an instance of CheckBox and because of runTouchApp expecting a widget to run I can use Builder.load_string.

The background of load_string handles basically every kv string and if there is a single instance of a widget defined (e.g. CheckBox), then it is elevated to a root widget position, for example:

Application
    openGL Window
        root widget(mostly layout)
            main tree
            and some widgets
            ...
share|improve this answer

Ruby with Shoes, 16 characters

Shoes.app{check}

Sample output: checkbox created with Ruby

share|improve this answer
    
+1 for Rubies with a side of Shoes! – CraigR8806 yesterday

HTML with JavaScript, 46 33 28 bytes

<body onclick=innerHTML^=1>0

v2

<body onclick=this.innerHTML^=1>0

v1

<body onclick=t=this;t.innerHTML=t.e=!t.e||''>

This is a variant on @ElPedro's answer: Create a Checkbox . Got down to 28 bytes with the help of @Albert Renshaw It could be further reduced, but that would make it identical to Create a Checkbox

The whole application area is clickable. It will display 0 in the off state and 1 in the on state. Try it out at https://jsbin.com/nuhetiyocu/1/edit

share|improve this answer
1  
Here's a neat variation at 39 bytes. <body onclick=t=this;t.innerHTML^=t?1:0 The 16 pixel rule between state change is up for debate though. – Albert Renshaw 18 hours ago
    
38 <body onclick=this.innerHTML^=this?1:0 – Albert Renshaw 18 hours ago
1  
Oh no with your help I'm down on 33 already :) – Jan 18 hours ago
1  
28 <body onclick=innerHTML^=1>0 – Albert Renshaw 18 hours ago
1  
Now that there's always a value inside the container, it could be changed from the body to a different element. But I just noticed that would make it identical to another answer codegolf.stackexchange.com/questions/109155/create-a-checkbo‌​x/… so I'm just leaving it as is – Jan 18 hours ago

Powershell v5+, 94 Bytes

($a=[Windows.Forms.Form]::new()).Controls.Add([Windows.Forms.Checkbox]::new());$a.ShowDialog()

enter image description here enter image description here

This is pretty terrible, but I can't get the statements any shorter with either Add-Type or using namespace - and the variable is required, since I need to reuse the object to show the form, and Controls.Add() returns nothing usable.

ShowDialog is required on my system to have the box be interactive after running this command, otherwise the form is frozen.

also System.Windows.Forms.Form can only be shortened to Windows.Forms.Form before (at least my own) system stops auto completing it in a fresh session.

share|improve this answer
    
Nice! Might want to add that this requires version 5+. – briantist yesterday
    
@briantist updated, thanks. – ConnorLSW yesterday

Any version of Windows command line, 3 bytes

(cmd.exe, batch, powershell, start->run, whatever)

osk

Opens the on-screen-keyboard which has several "checkboxes" such as shift, ctrl, alt, capslock keys Similar to the xgc answer, and inspired by the SmileBASIC answer screenshot.

share|improve this answer

AutoIt, 78 Bytes

GUICreate(0)
GUISetState(GUICtrlCreateCheckbox(0,0,0))
Do
Until GUIGetMsg()=-3

Opens a maximized window that can be closed like any other windows window. The maximization and ... on-top-ness is a side effect of the golfing.

enter image description here

share|improve this answer
    
How would I run this on Linux? – wat 9 hours ago
    
@wat wine AutoIt3.exe script.au3, where the script.au3 file contains this code. – mınxomaτ 8 hours ago
    
Thanks for the Wine tip – wat 7 hours ago

Python, 62 bytes

from tkinter import*
a=Tk()
Checkbutton(a).pack()
a.mainloop()
share|improve this answer

SmileBASIC, 49 bytes

@L
O=T
TOUCH OUT T,,
X=T<O!=X
KEY 1,""[X]GOTO@L

and are an empty box and a checked box in SB's font.
Toggle the checkbox by touching the screen (the closest thing to clicking with a mouse)

enter image description here enter image description here

share|improve this answer
    
This is just brilliant, though I don't really understand what the 4th line is doing. Could you explain? – snail' 2 hours ago
    
T<O is true when you stop touching the screen, and != is used as a logical XOR. X=X XOR (O && !T) – 12Me21 2 hours ago

Pug, 20 bytes

input(type=checkbox)
share|improve this answer
    
Besides which I count is as 23. If you remove the quotes it still works on Firefox and Chrome (can't test on IE) and would come in at 21 in which case I would consider it an improvement on the example and therefore valid. – ElPedro 2 days ago
1  
Whoops, sorry guys. I had no idea that there was an HTML example in the question. I changed my answer now. – theonlygusti 2 days ago
    
@ElPedro well, it would have been valid anyway... – theonlygusti 2 days ago
    
@heonlygusti - indeed but without the quotes I would have upvoted :-) btw, the downvote wasn't me. – ElPedro 2 days ago
    
I would have up-voted if it wasn't for those quotes, which are not needed. – NightSkyCode yesterday

Clojure, 201 195 145 bytes

(ns c(:require[quil.core :as q]))(def a(atom nil))(q/defsketch b :draw #(apply q/background(if @a[0 0 0][255 0 0])):mouse-clicked #(swap! a not))

-6 bytes by getting rid of the need for m/fun-mode.

-50 bytes by removing the :setup and :size options, since they are defaultable and unnecessary in non-fun-mode. Also removed the unnecessary import for middleware.

Creates a Quil sketch (a Clojure library that provides a layer over Processing), therefore, this requires the Quil library to run.

(ns bits.golf.checkbox
  (:require [quil.core :as q]))

; Mutable global variable to hold the toggle state
(def a (atom nil))

(q/defsketch b
         ; Draw the background color to be either black or red depending on the toggle state.
         :draw #(apply q/background (if @a [0 0 0] [255 0 0]))

         ; Negate the state on mouse click
         :mouse-clicked #(swap! a not))

enter image description here

enter image description here

share|improve this answer

Slim, 21 Bytes

input type="checkbox"

Try it here

So yeah. One of slim's major features is that < and > characters are not there. So basically, I get 2 bytes less than the creator of the question!

share|improve this answer
    
HTML still beats it though :) codegolf.stackexchange.com/a/109189/44888 – Jan 2 days ago
    
remove quotes for better points – wat 19 hours ago

Bash + zenity, 31

zenity --checklist --column a a

enter image description here

enter image description here

share|improve this answer

Bash (+yad), 23 bytes

Golfed

yad --form --field :chk

YAD is a program that will display GTK+ dialogs, and return (either in the return code or on standard output) the users input. This allows you to present information, and ask for information from the user, from all manner of shell scripts.

Yad is available in Debian and Ubuntu repositories (and probably others).

Demo

enter image description here

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.