At present we inhabit in jquery and kendoui world.
There you deal with MVVM design pattern and build you page from blocks. To avoid conflicts you usually restrict yourself from assigning ids to elements, as they make code reuse somewhat problematic.
But what if you have a label that you would like to associate with an input. In plain html you would write:
<label for="my-input">My label:</label> <input id="my-input" type="text">
Html spec suggests to use element id to build such an association.
So, how to avoid introduction of id, and to allow to select input while clicking on the label?
In our projects we use a little utility function that solves exactly this task. It's easier to quote an example than to describe implementation:
<!DOCTYPE html> <html> <head> <title>Label</title> <script src="scripts/jquery.js"></script> </head> <body> <div class="view"> <div>A template:</div> <table> <tr> <td><label data-for="[name=field1]">Name1:</label></td> <td><input name="field1" type="text" /></td> </tr> <tr> <td><label data-for="[name=field2]">Name2:</label></td> <td><input name="field2" type="text" /></td> </tr> <tr> <td><label data-for="[name=field3]">Name3:</label></td> <td><input name="field3" type="text" /></td> </tr> <tr> <td><label data-for="[name=field4]">Name4:</label></td> <td><input name="field4" type="checkbox" /></td> </tr> <tr> <td><label data-for="[name=field5][value=0]">Name5:</label></td> <td><input name="field5" value="0" type="radio" /></td> </tr> <tr> <td><label data-for="[name=field5][value=1]">Name6:</label></td> <td><input name="field5" value="1" type="radio" /></td> </tr> </table> </div> <script> $(document).on( "click", "label[data-for]", function(e) { var target = $(e.target); target.closest(target.attr("data-view") || ".view"). find(target.attr("data-for")). filter(":visible:enabled").first().click().focus(). filter("input[type=checkbox],input[type=radio]").change(); }); </script> </body> </html>
Remember Me
a@href@title, b, blockquote@cite, em, i, strike, strong, sub, super, u