Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Backbone.js - What is the best way to check a checkbox

My backbone model has a boolean value (isRegistered). When I render out the view I want to have a checkbox checked or unchecked depending on the true/false value of the boolean.

My current effort looks like this:

<input id="isRegisteredCheckbox" checked="<%= isRegistered ? 'checked': ''"/>

this doesn't work because according to the W3C Specification the checked attribute needs to be completely removed to uncheck a checkbox.

How do I do it using backbone template?

like image 489
reach4thelasers Avatar asked Apr 25 '12 10:04

reach4thelasers


2 Answers

You could use a test to enclose checked='checked'

<input id="isRegisteredCheckbox" <% if (isRegistered) { %>checked="checked"<% } %> />
like image 75
nikoshr Avatar answered Sep 21 '22 12:09

nikoshr


You don't need the checked= part. just print out checked in the tag if it needs to be checked.


EDIT

Now that we've determined that just printing "checked" out is valid html, you might try for simplicity:

render:

var registered;
var tmpl = _.template(your template);
isRegistered ? registered = 'checked' : registered = '';
var tmpl_data = _.extend(this.model.toJSON(), {registered: registered}); // or whatever values you need to add
$(this.el).html(tmpl(tmpl_data));

template:

<input type="checkbox" {{ registered }}>

No need for messy conditionals in your template using this method.

like image 27
tkone Avatar answered Sep 20 '22 12:09

tkone