Daniel Sh.
Daniel Sh.

Reputation: 2074

Set Handlebar class on the fly

I'd like to update the class of a div according to the user input. A simple input text that need to be validated. I have to go with a helper but I can't figure it out.

<div class="{{validationClass}}">   
    <p>{{input type="text" id="titleInput" value=title placeholder="Title"}}</p>
</div>

When there's nothing written in the text field I'd like to surround the box with the red colour, after the used typed a single character I want it to go default. So, according to bootstrap 2.x I'd need to set the div class to control-group error or control-group success etc.

I've never created a helper so I'm struggling, I don't know how to call it and how to return the desired string to be replaced in {{validationClass}}

Thanks.

Upvotes: 1

Views: 169

Answers (2)

selvagsz
selvagsz

Reputation: 3872

Use {{bind-attr}} helper

{{!hbs}}
 <div {{bind-attr class=":control-group isError:error"}}>
  {{input type="text" class="form-control" value=testVal}}
 </div>

//Controller
App.ApplicationController = Em.Controller.extend({
  testVal: '',
  isError: Em.computed.empty('testVal')
});

Sameple Demo

Upvotes: 1

Marcio Junior
Marcio Junior

Reputation: 19128

You can use the bind-attr helper .

This is a sample:

<script type="text/x-handlebars" data-template-name="index">
  <div {{bind-attr class=":control-group validationClass"}}>   
    <p>{{input type="text" id="titleInput" value=title placeholder="Title"}}</p>
  </div>
</script>

App.IndexController = Ember.ObjectController.extend({
    title: null,
    validationClass: function() {
        var title = this.get('title');
        return title ? 'success' :  'error';
    }.property('title')
});

http://jsfiddle.net/marciojunior/6Kgty/

Upvotes: 2

Related Questions