开发者

What's the purpose of the for attribute in HTML?

I understand the for attribute specifies which form element a lab开发者_C百科el is bound to.

Do you have an example where this would be actually useful?


It's most useful for a checkbox label where it will make the whole label clickable so you don't have to target the checkbox itself to toggle its state. Same for radio buttons.


<label for="email">E-mail:</label>
<input type="text" id="email" name="email"/>

Now if you click on "E-mail", the corresponding input element will get focused.


<label for="name">Name</label>

<input type="text" id="name" />

http://jsfiddle.net/jRB2s/3/

Clicking on the label will give focus to the element with the same ID as the for value.

For radio buttons or checkboxes, it will toggle their status as if you were clicking on them.

This is really useful expecially on handheld devices, where it's not always simple to click the desired form control.


It's there for semantic purposes. It's useful for screen readers and such as well as, potentially, search engines. Browsers will also connect controls to their labels (e.g. checkboxes will activate when clicking a label) and you can apply shortcut keys to labels which will focus their controls when pressed.

There are two formats for labels:

<label>Label<input ... /></label> 

which doesn't require a for attribute. And

<label for="control">Label</label>
<input id="control" name="control" ... />

which may be required when the label and input are separated (e.g. a table).

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜