knockout.js checkboxes used to control enabled/disabled state of input fields - javascript

I am trying to bind a checkbox to each line in a list of objects, in a very similar fashion to a question asked/answered here: Binding a list of objects to a list of checkboxes
Essentially, as follows:
<ul data-bind="foreach: phones">
<li>
<input type='text' data-bind="attr: {value:phone}, disable: $root.selectedPhones"/>
<input type="checkbox" data-bind="attr: {value:id}, checked: $root.selectedPhones" />
</li>
</ul>
<hr/> selected phones:
<div data-bind="text: ko.toJSON($root.selectedPhones)"></div>
<hr/> phones:
<div data-bind="text: ko.toJSON($root.phones)"></div>
with js as follows:
function Phone(id,phone) {
this.id = id;
this.phone = phone;
}
var phones_list = [
new Phone(1, '11111'),
new Phone(2, '22222'),
new Phone(3, '33333')
];
var viewModel = {
phones: ko.observableArray(phones_list),
selectedPhones: ko.observableArray()
};
ko.applyBindings(viewModel);
The idea being that in the initial state, all of the input boxes are disabled and that clicking a checkbox will enable the input box in that row.
The data is coming from a fairly deeply nested object from the server-side so I'd like to avoid 'padding' the data with an additional boolean ie avoiding new Phone(1,'xx', false)
(a) because it's probably unnecessary (b) because the structure is almost certainly going to change...
Can the selectedPhones observable be used by the enable/disable functionality to control the status of fields in that 'row'?
Hope someone can help....
I have a jsfiddle here

You can create a small helper function which checks that a given id appers in the selectedPhones:
var viewModel = {
phones: ko.observableArray(phones_list),
selectedPhones: ko.observableArray(),
enableEdit: function(id) {
return ko.utils.arrayFirst(viewModel.selectedPhones(),
function(p) { return p == id })
}
};
Then you can use this helper function in your enable binding:
<input type='text' data-bind="attr: {value:phone}, disable: $root.enableEdit(id)"/>
Demo JSFiddle.

Related

cant make an object I added to a knockout model observable

Here is the fiddle demonstrating the problem http://jsfiddle.net/LkqTU/31955/
I made a representation of my actual problem in the fiddle. I am loading an object via web api 2 and ajax and inserting it into my knockout model. however when I do this it appears the attributes are no longer observable. I'm not sure how to make them observable. in the example you will see that the text box and span load with the original value however updating the textbox does not update the value.
here is the javascript.
function model() {
var self = this;
this.emp = ko.observable('');
this.loademp = function() {
self.emp({
name: 'Bryan'
});
}
}
var mymodel = new model();
$(document).ready(function() {
ko.applyBindings(mymodel);
});
here is the html
<button data-bind="click: loademp">
load emp
</button>
<div data-bind="with: emp">
<input data-bind="value: name" />
<span data-bind="text: name"></span>
</div>
You need to make name property observable:
this.loademp = function(){
self.emp({name: ko.observable('Bryan')});
}

Bind a checkbox to a plain string in Knockout.js

In my viewmodel i have tons of checkboxes bound to plain strings:
<input type="checkbox" value="CODE" data-bind="checked: itemValue" />
Until now, i'm using an observable array to resolve the true/false value of the checkbox to the value that i need:
var viewModel = {
itemValue: ko.observableArray()
};
Which is the simplest and shortest way, if there is one, to bind a checkbox to a string value without the need to reference it as itemValue[0] ?
What i need is the string value if checked, null if unchecked.
Due to the large amount of observables in my viewmodel, i would avoid to use tons of conditions like if(itemValue) ...
Fiddle using an observableArray: https://jsfiddle.net/wu470qup/
If you want effortless markup, you'll have to keep track of the checkboxes you want to render in your viewmodel. Here's the easiest example:
allValues is a regular array of strings. Each of these strings will get a checkbox. itemValues is an observable array of the strings that have a checked checkbox. correctedValues is a computed array with null for each unchecked box, and a string for each checked one.
Notice that I use $data to refer to the current string value in the foreach.
var allValues = ["CODE", "ANOTHER_VAL"];
var itemValues = ko.observableArray();
var correctedValues = ko.computed(function() {
var all = allValues;
var checked = itemValues();
return all.map(function(val) {
return checked.indexOf(val) === -1 ? null : val;
});
});
var viewModel = {
allValues: allValues,
itemValues: itemValues,
correctedValues: correctedValues
};
ko.applyBindings(viewModel);
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.2.0/knockout-min.js"></script>
<!-- ko foreach: allValues -->
<label>
<input type="checkbox" data-bind="checked: $parent.itemValues, checkedValue: $data" />
<span data-bind="text: $data"><span/>
</label>
<!-- /ko -->
<pre data-bind="text: ko.toJSON($data, null, 2)"></pre>
A more elegant approach would be to create viewmodels for each checkbox. For example:
var CheckboxItem = function() {
this.label = ko.observable("CODE");
this.checked = ko.observable(false);
this.id = ko.computed(function() {
return this.checked() ? this.label() : null;
}, this);
};
With the HTML template:
<label>
<input type="checkbox" data-bind="checked: checked" />
<input data-bind="value: label" />
</label>
Then, in the parent viewmodel, you can store an observable array of CheckBoxItems and have a computed array that holds all id properties.

How to get selected checkboxes on button click in angularjs

I want to do something like this
<input type="checkbox" ng-model="first" ng-click="chkSelect()"/><label>First</label>
<input type="checkbox" ng-model="second" ng-click="chkSelect()"/><label>Second</label>
<input type="checkbox" ng-model="third" ng-click="chkSelect()"/><label>Third</label>
<input type="checkbox" ng-model="forth" ng-click="chkSelect()"/><label>Forth</label>
<button>Selected</button>
On button click I want to display selected checkbox labelname.
$scope.chkSelect = function (value) {
console.log(value);
};
Because the checkboxes are mapped, you can reference $scope.first, $scope.second, etc in your chkSelect() function. It's also possible to have a set of checkboxes mapped as a single array of data instead of having to give each checkbox a name. This is handy if you are generating the checkboxes, perhaps from a set of data.
I agree with Bublebee Mans solution. You've left out a lot of detail on why you're trying to get the label. In any case if you REALLY want to get it you can do this:
$scope.chkSelect = function (value) {
for(var key in $scope){
var inputs = document.querySelectorAll("input[ng-model='" + key + "']");
if(inputs.length){
var selectedInput = inputs[0];
var label = selectedInput.nextSibling;
console.log(label.innerHTML);
}
};
};
You can mess around with it to see if it's indeed selected.
fiddle: http://jsfiddle.net/pzz6s/
Side note, for anybody who knows angular please forgive me.
If you are dealing with server data, you might need isolated html block and deal with data in controller only.
You can do it by creating array in controller, maybe your data from response, and use ngRepeat directive to deal independently in html code.
Here is what I am telling you:
HTML:
<form ng-controller="MyCtrl">
<label ng-repeat="name in names" for="{{name}}">
{{name}}
<input type="checkbox"
ng-model="my[name]"
id="{{name}}"
name="favorite" />
</label>
<div>You chose <label ng-repeat="(key, value) in my">
<span ng-show="value == true">{{key}}<span>
</label>
</div>
</form>
Javascript
var myApp = angular.module('myApp',[]);
function MyCtrl($scope) {
$scope.names = ['pizza', 'unicorns', 'robots'];
$scope.my = { };
}
You want to have something like the following in your controller (untested, working from memory):
$scope.checkBoxModels = [ { name: 'first', checked: false }, { name: 'second', checked: false }, { name: 'third', checked: false }, { name: 'fourth', checked: false } ];
Then in your view:
<input ng-repeat"checkboxModel in CheckBoxModels" ng-model="checkBoxModel.checked" ng-click="chkSelect(checkBoxModel)" /><label>{{checkBoxModel.name}}</label>
Then update your function:
$scope.chkSelect = function (checkBoxModel) {
console.log(checkBoxModel.name);
};

knockout checked binding - only one checked

I have a list of Admins with a check box. I want to be able to select only one Admin.
HTML:
<tbody data-bind="foreach: people">
<tr>
<td>
<input type="checkbox" data-bind="attr: { value: id }, checked: $root.selectedAdmin">
<span data-bind="text: name"/>
</td>
</tr>
</tbody
JS:
function Admin(id, name) {
this.id = id;
this.name = name;
}
var listOfAdmin = [
new Admin(10, 'Wendy'),
new Admin(20, 'Rishi'),
new Admin(30, 'Christian')];
var viewModel = {
people: ko.observableArray(listOfAdmin),
selectedAdmin: ko.observableArray()
};
ko.applyBindings(viewModel);
For Example if Admin id 10 is selected the other admins should be deselected.
Is that Possible to do with Knockout?
You should really use radio buttons if you only want to allow multiple selection.
However if you still want to use checkboxes then on solution would be to combine the checked and the click binding:
Use the checked to check only when the current id equal to the selectedAdmin property and use the click binding to set the selectedAdmin.
So you HTML should look like this:
<input type="checkbox" data-bind="attr: { value: id },
checked: $root.selectedAdmin() == id,
click: $parent.select.bind($parent)" />
And in your view model you just need to implement the select function:
var viewModel = {
people: ko.observableArray(listOfAdmin),
selectedAdmin: ko.observableArray(),
select: function(data) {
this.selectedAdmin(data.id);
return true;
}
};
Demo JSFiddle.
Notes:
the return true; at the end of the select function. This is required to trigger the browser default behavior in this case to check the checkbox.
the .bind($parent) is needed to set the this in the select function to be the "parent" viewModel object.

Create checkbox list from array of objects with knockout

I would like to know what is the proper way to create a list of checkboxes bound to a selected list for an array of objects using knockout. It is very straight forward using basic values like a list of words but can it be done with an array of objects.
this works:
<script type="text/JavaScript">
function ViewModel(){
self.choices = ["one","two","three","four","five"];
self.selectedChoices = ko.observableArray(["two", "four"]);
self.selectedChoicesDelimited = ko.dependentObservable(function () {
return self.selectedChoices().join(",");
});
}
</script>
<ul class="options" data-bind="foreach: choices">
<li><input type="checkbox" data-bind="attr: { value: $data }, checked: selectedChoices" /><span data-bind="text: $data"></span></li>
</ul>
<div data-bind="text: selectedChoicesDelimited"></div>
But I can't figure out how to get it to work if the items are objects like this:
self.choices = [{"Id":1,"Name":"one"},{"Id":2,"Name":"two"}, {"Id":3,"Name":"three"}, {"Id":4,"Name":"four"}, {"Id":5,"Name":"five"}];
self.selectedChoices = ko.observableArray([{"Id":2,"Name":"two"}, {"Id":4,"Name":"four"}]);
In the end I would like to be able to create checkbox lists from MultiSelectList object created in my MVC controller and passed to the view in the ViewBag.
#ebohlman answer about using CheckedValue is what I was looking for. One other note however, is that specifying the SelectedChoices directly as I did above will not work because the objects will not equal the objects in the Choices array even though the values in them are the same. Instead I've added code to push the selected choices onto the SelectedChoices array after defining it:
self.choices = [{"Id":1,"Name":"one","Selected":true},{"Id":2,"Name":"two","Selected":false}];
self.selectedChoices = ko.observableArray();
$.each(self.choices, function (index, value) {
if(value.Selected) self.selectedChoices.push(value);
});
Use the checkedValue binding:
<li>
<input type="checkbox" data-bind="checkedValue: $data, checked: $root.selectedChoices" />
<span data-bind="text: Name"></span>
</li>
And pick out the Name values when calculating the delimited string:
self.selectedChoicesDelimited = ko.computed(function () {
return ko.utils.arrayMap(self.selectedChoices(), function(v) {
return v.Name;
}).join(",");
});

Categories

Resources