Sunday 24 November 2019

forms - What does "for" attribute do in HTML tag?



I wonder what is the difference between the following two code snippets:








and








I'm sure it does something when you use a special JavaScript library, but apart from that, does it validate the HTML or required for some other reason?


Answer



The tag allows you to click on the label, and it will be treated like clicking on the associated input element. There are two ways to create this association:



One way is to wrap the label element around the input element:







The other way is to use the for attribute, giving it the ID of the associated input:







This is especially useful for use with checkboxes and buttons, since it means you can check the box by clicking on the associated text instead of having to hit the box itself.



Read more about this element in MDN.



No comments:

Post a Comment

php - file_get_contents shows unexpected output while reading a file

I want to output an inline jpg image as a base64 encoded string, however when I do this : $contents = file_get_contents($filename); print &q...