49

I can't seem to find an example anywhere... what's the correct way of doing a HTML5 checkbox?

bpeterson76
  • 12,918
  • 5
  • 49
  • 82
Skizit
  • 43,506
  • 91
  • 209
  • 269

2 Answers2

76

As far as I know and the docs state, nothing fundamental has changed. The basic markup is

<input name="your_name" value="your_value" type="checkbox">

What is new is some interesting properties.

  • form - a reference to the form the control is associated with (nice!)
  • autofocus - to be focused as soon as the document is loaded (nice!)
  • required - require that it be checked (super nice! Although it isn't supported by Internet Explorer or Safari (yet).)
Chuck Le Butt
  • 47,570
  • 62
  • 203
  • 289
Pekka
  • 442,112
  • 142
  • 972
  • 1,088
  • 1
    +1 "super nice! Although I don't entirely understand how this makes sense for a checkbox." very true.. good catch... shall i ask an SO question on that? – naveen Feb 04 '11 at 18:18
  • @yet why not, would be interesting to know! – Pekka Feb 04 '11 at 18:20
  • 3
    http://stackoverflow.com/questions/4901576/html5-significance-of-attribute-named-required-in-checkbox-radio – naveen Feb 04 '11 at 18:30
  • 5
    For checkboxes, the required attribute shall only be satisfied when one or more of the checkboxes with that name in that form are checked. For radio buttons, the required attribute shall only be satisfied when exactly one of the radio buttons in that radio group is checked. – The Surrican Feb 04 '11 at 19:03
  • 1
    The problem with @Joe Hopfgartner's quote is that it comes from a currently unauthoritative source: http://www.whatwg.org/specs/web-forms/current-work/ That's the old Web Forms 2 work; the top of the doc admits that it's been superseded by HTML5. Don't base your expectations on that document! – james.garriss Oct 14 '11 at 12:18
  • @JoeHopfgartner, @james.garriss: I'd expect that `required` for a HTML5 checkbox means it can't be *[indeterminate](http://css-tricks.com/indeterminate-checkboxes/)*, but I've no reference for that. – l0b0 Apr 10 '12 at 13:47
5

A more complete example - and avoiding the long stream of posts to How to check whether a checkbox is checked in jQuery?.

HTML

<input id="your_id" name="your_name" value="your_value" type="checkbox">

Optionally add the 'checked' attribute to default to checked on load.

<input id="your_id" name="your_name" value="your_value" type="checkbox" checked>

JavaScript

$('#your_id').is(':checked')        // Returns a Boolean TRUE if checked

e.g.

if ($('#your_id').is(':checked')) {
    // Checkbox was checked
}
Community
  • 1
  • 1
wolfstevent
  • 703
  • 8
  • 13
  • 7
    You're using jquery it should be mentioned, though it is a javascript library it is not javascript. – Vignesh Jun 17 '14 at 05:14