Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using Ember.js text field ids for a <label> tag

A label tag is of the form:

<label for="id_of_text_field">
<input type="text" name="example" id="id_of_text_field" />

Where the for tag of the label and the id tag of the text field need to match. I had two ideas to make this work in my Ember.js template:

Idea #1: I tried to make a special binding named field_id to use in both the label and the TextField. I executed this as follows:

<label {{bindAttr for="content.field_id"}}> {{content.label}}</label>
{{view Ember.TextField valueBinding="content.data" id="content.field_id"}}

Unfortunately only the label's id renders correctly. The TextField's id does not render correctly and turns out to be "metemorph... something-or-other".

Idea #2: To somehow conjure the TextField's id and use that for the label tag, but I'm afraid at some point the TextField's id will not be ready when the label tag is rendered. Even if this were not an issue, I do not know how to find the TextField's id from JS.

This is in a template so I will have more than one of these label/TextField pairs.

How can I get the label's for tag to match up with the TextField's id tag with Ember.js?

Thank you!

UPDATE

Using Peter Wagenet's advice and slight modification, I did the following:

<label {{bindAttr for="textField.elementId"}}> {{content.label}}</label>
{{view Ember.TextField valueBinding="content.value" viewName="textField"}}

Using this technique users can now click labels to select TextFields, CheckBoxes, and Selects.

like image 295
shs Avatar asked May 06 '12 04:05

shs


2 Answers

First off, the Metamorph tag is for the label's value. It's not related to the field's id. However, this code still won't work because standard properties don't do anything special with property paths. In this case, the value of id, is literally content.field_id. This is certainly not what you wanted. In normal circumstances, you could use elementIdBinding (id is just an alias for elementId), however the element ids for Ember Views cannot be changed after creation so that approach won't work here.

One possible solution makes use of the viewName property. The viewName property provides a named reference to the view on the parentView. You could then, do the following:

<label {{bindAttr for="view.textField.field_id"}}> {{content.label}}</label>
{{view Ember.TextField valueBinding="content.data" viewName="textField"}}
like image 149
Peter Wagenet Avatar answered Oct 02 '22 12:10

Peter Wagenet


This won't always solve your problem, but I just wanted to add that simply nesting the input inside the label is often a convenient solution, since it allows you to drop the for attribute altogether (reference).

like image 45
Jo Liss Avatar answered Oct 02 '22 12:10

Jo Liss