Vinit Patel
Vinit Patel

Reputation: 2464

How to set Checkbox by default checked in treeview

I am trying to set treeview with checkbox and there are some check box are by default checked , here my data source value:-

[{"id":12,"Name":"Shirts","hasChildren":false,"Checked":true}
,{"id":13,"Name":"Jeans","hasChildren":false,"Checked":false},
{"id":14,"Name":"Shoes","hasChildren":false,"Checked":true},
{"id":15,"Name":"Apparel accessories","hasChildren":false,"Checked":false}]

and my view page code:--

                       $(document).ready(function() {
                        $("#category-treeview").kendoTreeView({
                            dataSource: categories,
                            dataTextField: "Name",
                            checkboxes: true
                    });
                });

but i no one checkbox is selected why?

Can any advice how to solve this?

Regards, vinit

Upvotes: 0

Views: 10118

Answers (2)

OnaBai
OnaBai

Reputation: 40887

Your code is basically correct. The only problem is that Checked needs to be checked (lowercase). Your data would look like:

var categories = [
    {"id":12,"Name":"Shirts","hasChildren":false,"checked":true},
    {"id":13,"Name":"Jeans","hasChildren":false,"checked":false},
    {"id":14,"Name":"Shoes","hasChildren":false,"checked":true},
    {"id":15,"Name":"Apparel accessories","hasChildren":false,"checked":false}
];

I put your code with this small change here: http://jsfiddle.net/OnaBai/78k2b/

Upvotes: 3

Robin Giltner
Robin Giltner

Reputation: 3055

If all you need to do is show whether the checkbox is checked or not, you can easily employ a templateFunction for the checkbox.

checkboxes: {
    template: checkboxTemplate
}

And use a function something like

function checkboxTemplate(e) {
  if(e.item.Checked) {
    return "<input type='checkbox' checked='checked' />";
  } 
  else {
    return "<input type='checkbox' />";
  }
}

The issue with this approach, is there isn't a two-way data-binding happening. So if you change a checkbox, and them dump the dataSource, that change isn't reflected.

If you are needing two-way data-binding, so you can post the changes back, you will need to employ something quite a bit more complicated. It is laid out pretty well in this SO post (Binding checkboxes in treeview with checkboxes that uses remote datasource).

I have looked for a more elegant answer to this, as it would seem fairly common, but haven't found anything yet.

Upvotes: 2

Related Questions