ember.jsember.js-view

Ember.js: how to get input element ID for use in label


I have a scenario where I can't wrap the label around an input element, so it has to look something like this:

<label>Name</label>
{{input value=name}}

I'd like to set the label's for attribute to match the input element's ID so that the rendered output is something like this:

<label for="ember351">Name</label>
<input type="text" value="" id="ember351" />

How can I get a reference to the element ID? I've seen some solutions where you use an Ember.TextField view, but I'm looking for a solution that supports the input helper (i.e. {{input}})


Solution

  • You can scope a custom ID for the input element to the current view by using the component / view ID as a prefix. This will help you avoid naming collisions outside the view. You'll need a concat helper (included as of Ember v1.13.x). Or you can always create one, of course.

    <label for="{{concat elementId '-name'}}">Name</label>
    {{input value=name id=(concat elementId '-name')}}
    

    Should render something like:

    <label for="ember351-name">Name</label>
    <input type="text" value="" id="ember351-name />