Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

using handlebars bindAttr for checkbox

I'm using handlebars in a backbone.js rails app, and I have a Boolean field I'm populating with a checkbox.

When I load the edit page, the form is populated with the contents from the server JSON something like

{id:3,user:'test',checkbox:1}

now in my handlebar form, I want to show that the checkbox is 1.

< input type="checkbox" name="checkbox" value="1" {{#if checkbox}} {{bindAttr checkbox checked="isSelected"}}{{/if}} >

but this isn't returning the checked checkbox. I'd really like to just be able to say if checkbox==1, but I don't see how I can do that with handlebars.

Anysuggestions??

like image 451
pedalpete Avatar asked Jan 30 '12 13:01

pedalpete


2 Answers

What you would usually do, is using a Boolean in the 'model'.

{
    isChecked: true
}

and then

<input type="checkbox" {{bindAttr checked="isChecked"}}>

If the Boolean is true, it will render the checked property, and if the Boolean is false, it would omit the property. So if isChecked is true, then Handlebars would output

<input type="checkbox" checked>

and if isChecked were false, we would get

<input type="checkbox">

Which is what we want!

like image 56
Willem Mulder Avatar answered Nov 06 '22 08:11

Willem Mulder


I also wrote a helper to do this. It doesn't use backbone.js, so may be an alternative for some:

Handlebars.registerHelper('checked', function(currentValue) {
    return currentValue == '1' ? ' checked="checked"' : '';
});

Usage example:

<input type="checkbox" name="cbxExample" id="cbxExample" {{checked cbxExample}}/>

Would tick a checkbox if the supplied JSON was:

{"cbxExample" : "1"}

Resulting in:

<input type="checkbox" name="cbxExample" id="cbxExample" checked="checked" />

[my first post - hope that's helpful!]

like image 41
Matt Avatar answered Nov 06 '22 08:11

Matt