Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Correct way to do HTML5 checkbox

Tags:

html

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

like image 233
Skizit Avatar asked Feb 04 '11 18:02

Skizit


People also ask

What is the correct HTML for checkbox?

The <input type="checkbox"> defines a checkbox. The checkbox is shown as a square box that is ticked (checked) when activated. Checkboxes are used to let a user select one or more options of a limited number of choices. Tip: Always add the <label> tag for best accessibility practices!

How do you name a checkbox in HTML?

The Input Checkbox name property in HTML DOM is used to set or return the value of name attribute of a input checkbox field. The name attribute is required for each input field. If the name attribute is not specified in an input field then the data of that field would not be sent at all.

How do I make a checkbox checked by default in HTML?

If you wanted to submit a default value for the checkbox when it is unchecked, you could include an <input type="hidden"> inside the form with the same name and value , generated by JavaScript perhaps.


2 Answers

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).)
like image 171
Pekka Avatar answered Sep 28 '22 11:09

Pekka


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 } 
like image 40
wolfstevent Avatar answered Sep 28 '22 10:09

wolfstevent