Reputation: 57602
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}})
Upvotes: 10
Views: 6352
Reputation:
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 />
Upvotes: 13
Reputation: 10084
To flesh out these answers there is a more flexible way by use of an HTMLBars helper:
<div class="form-group">
<label for="{{guid-for this "name"}}">Your name:</label>
{{input id=(guid-for this "name")
type="text"
value=value
placeholder="Enter your name…"}}
</div>
The app/helpers/guid-for.js
HTMLBars helper could look like this:
import Ember from 'ember';
export default Ember.Helper.helper(function([obj, suffix]) {
Ember.assert('Must pass a valid object', obj);
return [Ember.guidFor(obj), suffix].join('-');
});
Upvotes: 4
Reputation: 1273
You can still set the id with input helpers. So
<label for="name">Name</label>
{{input value=name id="name"}}
will result in
<label for="name">Name</label>
<input type="text" value="" id="name">
Upvotes: 4