Monday, September 3, 2012

Radio button list with knockout.js

Below is a quick example of radio button list with knockout.js-
<script src="http://knockoutjs.com/js/knockout-2.1.0.js" type="text/javascript"></script>

<table>
    <tr>
        <td>
            <div data-bind="foreach: items">
                <input type="radio" name="items" data-bind="attr: { value: id }, checked: $root.selected" />
                <span data-bind="text: name"></span>
            </div>
            <div data-bind="text: selected">
            </div>
        </td>
    </tr>
</table>
<script type="text/javascript">
    function RadioButton(id, name, selected) {
        this.id = id;
        this.name = name;
        this.selected = selected;
    }
    function RadioModel() {
        var self=this;
        self.items= [
            new RadioButton(1, "first", true),
            new RadioButton(2, "two", false),
            new RadioButton(3, "three", false),
        ];
        self.selected = ko.observable();
        self.onSubmit= function () {
            var x = self.selected();
        }
    };
    var viewModel = new RadioModel();
    $(function () {
        ko.applyBindings(viewModel);
        var selected = ko.utils.arrayFirst(viewModel.items, function (item) { return item.selected; });
        viewModel.selected(selected.id);
    });
</script> 
We can check this in jsFiddle here.

No comments:

Post a Comment