Instantly share code, notes, and snippets.
ntodorov/knockoutjs_bootstrap_radiobuttons_group.html
Last active Nov 18, 2015
knockoutjs, bootstrap and dynamic radio buttons group
<!DOCTYPE html> | |
<html> | |
<head> | |
<meta http-equiv="content-type" content="text/html; charset=UTF-8"> | |
<title>knockoutjs, bootstrap and dynamic radio buttons group - jsFiddle demo by ntodorov</title> | |
<script type='text/javascript' src='//code.jquery.com/jquery-2.1.3.js'></script> | |
<link rel="stylesheet" type="text/css" href="/css/result-light.css"> | |
<script type='text/javascript' src="http://knockoutjs.com/downloads/knockout-3.0.0.js"></script> | |
<script type='text/javascript' src="https://netdna.bootstrapcdn.com/bootstrap/3.2.0/js/bootstrap.min.js"></script> | |
<link rel="stylesheet" type="text/css" href="http://netdna.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css"> | |
<script type='text/javascript'>//<![CDATA[ | |
$(window).load(function(){ | |
ko.bindingHandlers.bsChecked = { | |
init: function (element, valueAccessor, allBindingsAccessor, | |
viewModel, bindingContext) { | |
var value = valueAccessor(); | |
var newValueAccessor = function () { | |
return { | |
change: function () { | |
value(element.value); | |
} | |
} | |
}; | |
ko.bindingHandlers.event.init(element, newValueAccessor, | |
allBindingsAccessor, viewModel, bindingContext); | |
}, | |
update: function (element, valueAccessor, allBindingsAccessor, | |
viewModel, bindingContext) { | |
if ($(element).val() == ko.unwrap(valueAccessor())) { | |
setTimeout(function () { | |
$(element).closest('.btn').button('toggle'); | |
}, 1); | |
} | |
} | |
} | |
var viewModel = { | |
items: ko.observableArray([ | |
{ id: 1, itemName: 'Choice 1' }, | |
{ id: 2, itemName: 'Choice 2' }, | |
{ id: 3, itemName: 'Choice 3' }, | |
{ id: 4, itemName: 'Choice 4' } | |
]), | |
chosenItem: ko.observable(2) | |
}; | |
ko.applyBindings(viewModel); | |
});//]]> | |
</script> | |
</head> | |
<body> | |
<div class="btn-group" data-toggle="buttons" data-bind="foreach: items"> | |
<label class="btn btn-primary"> | |
<input type="radio" name="options" data-bind="checkedValue: $data.id, bsChecked: $root.chosenItem" /> | |
<span data-bind="text: itemName"></span> | |
</label> | |
</div> | |
<pre data-bind="text: JSON.stringify(ko.toJS($root), null, 2)"></pre> | |
</body> | |
</html> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment