开发者

Partially select checkbox with javascript

开发者 https://www.devze.com 2023-03-10 21:28 出处:网络
Is there a way using Javascript and HTML(5) to make a checkbox be partially selected, like the checkboxes in a program installation menu when you select only some of the su开发者_运维技巧b options?HTM

Is there a way using Javascript and HTML(5) to make a checkbox be partially selected, like the checkboxes in a program installation menu when you select only some of the su开发者_运维技巧b options?


HTML5 defines the indeterminate boolean property.

I've tested it only in the latest Safari, Chrome, and Firefox. They all support the indeterminate state.

Example: http://jsfiddle.net/5tpXc/

Edit: Note that this wont work with older browsers and maybe not with current versions of IE. You'd need to rely on hacks as described in other answers here if you want to support all browsers.


HTML checkboxes (that is, input elements of type checkbox) don't have a third state (partially checked). So no, there is no direct way to do this.

What you'd probably have to do is make a custom checkbox-looking image and bind to its various events (click, for example) to store its current "state" in a hidden form field via JavaScript. You may run into a number of issues with this approach, though.

For example, keyboard navigation of the form may not be possible for this particular element. (Can one tab to an image and send it keyboard events? I'm not sure.)

Additionally, you could try manipulating custom attributes on a checkbox element via JavaScript to store a third state. But the rendering of the element itself has no visual indicator of something like that. You could probably manipulate its style (color, background color, border color, etc.) to try to mimic the visual behavior. But you may not be able to achieve the exact visual style that you're using for reference.

It's certainly an interesting prospect, and I'm intrigued enough that I may try to implement something like this in the near future. But with a native checkbox element, it's not possible. It has only two states.

Edit: Refer to @kassens' answer for doing this in HTML5. If you're limited to previous versions of HTML for any reason, then it's going to have to be a hack as described here. But if you can rely on users supporting HTML5, then it looks like native support is there.


Nope. You would have to make a custom checkbox graphic and fake it.

Edit: Refer to @Kassen's answer for a way to have partially checked boxes in HTML5-compliant browsers.

0

精彩评论

暂无评论...
验证码 换一张
取 消