3

Is it possible to toggle the state (check/uncheck) of an input type checkbox without using JavaScript/jQuery i.e. only through HTML and CSS?

Say I want to toggle it on click on a label next to it.

If yes, how can we achieve that?

4
  • I don't think it is possible. Under what circumstances would you like this toggle to happen? Commented Jul 29, 2017 at 18:45
  • with plain html you only need to click it to toggle checked and unchecked state, you do not need javascript for this !. Can you clarify your question cause css is only about styling. Commented Jul 29, 2017 at 18:46
  • Functional behaviour like this should be controlled by JavaScript. CSS should be used for presentation rather than controlling functionality. Hacks might exist with CSS but it would go against web semantics which really isn't recommended. Commented Jul 29, 2017 at 18:50
  • @andrewhiles: Yes surely, but I just wanted to know the workarounds/hacks. Commented Jul 29, 2017 at 19:00

4 Answers 4

8

If you need to check/uncheck the input from a <label>, set an id on the input, and use the label's for attribute to connect them.

<input type="checkbox" id="chk" />

<label for="chk">Click to check/uncheck</label>

Another option is to use the label as a container to the input:

<label><input type="checkbox" /> Click to check/uncheck</label>

Sign up to request clarification or add additional context in comments.

1 Comment

Yep, @GCyrillus has specified the second option.
1

label and input are meant to work together :)

see : https://www.w3.org/wiki/HTML/Elements/label

The caption can be associated with a specific form control:

<label for="a">toggle state</label><input type="checkbox" id="a"/>

1 Comment

Thanks for the documentation links! :)
1

This answer is for the question before it was updated!

Only using a hardcoded attribute checked:

<input type="checkbox" checked />

If you want to trigger it from code, it's impossible without JS/jQuery.

3 Comments

could be a good guess about what the OP really try to ask for ;)
@GCyrillus, i have answered the question before it was updated. When i answered, the question didn't contain the row "Say I want to toggle it on click on a label next to it". After the question update, Ori Drori already gave a good answer
@CommercialSuicide: Thanks for the initial question's answer :)
1

YES , You Can. Use this code

<label for="MyCheckBox">Click Me !</label>
<input type="checkbox" id="MyCheckBox" />

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.