How to check checkbox based on array value in knockout js - javascript

I'm doing knockout js. I have an array list coming from the database by making an ajax call and saving all the values in knockout observable array.
I'm looping through the array. Based on a value I want to check or uncheck the checkbox. Below is how I'm doing but this does not seems to be working. I can see values for roleid exists in the array but the checkbox is not checked if the value of roleid is true. What am i doing wrong here.
<tbody data-bind="foreach:$root.test">
<tr>
<div><input type="checkbox" value="1" data-bind="checked: roleid == 1"/></div>
</tr>
</tbody>

I think roleid needs to be observable. And then you can use
roleid() === 1
or
roleid() === true
whichever is appropriate for your case.

this will work if roleid is an observable and is set to a string value.
knockout "checked" compares only string values vs string values, so the value inside value="1" is considered a string.
so your checkbox will be checked if roleid is setup like this
viewModel.roleid = ko.observable("1");

You can use checkedValue binding and can assign the observableArray to checked binding.
From documentation
If your binding also includes checkedValue, this defines the value used by the checked binding instead of the element’s value attribute. This is useful if you want the value to be something other than a string (such as an integer or object), or you want the value set dynamically.
Here is the javascript code:
function viewModel()
{
var self = this;
//the array list which you can get from the server
self.items = ko.observableArray([
{ item: '1' },
{ item: '2' },
{ item: '3' },
{ item: '4' }
]);
//the array of items which you want to be checked
self.chosenItems = ko.observableArray(
[
self.items()[1],
self.items()[3]
]
);
}
Html code
<div data-bind="foreach: items">
<input type="checkbox"
data-bind="checkedValue: $data, checked: $root.chosenItems" />
<span data-bind="text: item"></span><br />
</div>
And here is the Js fiddle demonstrating the use.

Related

Angular checkbox to filter data

I am showing FreeEvents using checkbox. I am passing the value to the filter as filter:filterFreeEvent . This is working fine.
But I want to avoid passing value in the filter rather I want to use a change event of a checkbox to filter.
Something like
<input type="checkbox" ng-model="showFreeEvent" ng-change($event)">
This is my JsFiddle example.
Has anyone done something like this?. Any help or suggestion would be appreciated.
Thanks in advance
You can also change a variable in the change-event only like this :
<input ng-model="changeValue" ng-change="showFreeEvent = showFreeEvent== false ? true : false" value="" type="checkbox" />
If the showFreeEvent is false, ng-change will change it to true and vice-versa.
You can use ng-change to handle the checkbox change event. Then you can use Array.prototype.filter to filter your events. Filtered events should be stored in a separate variable. Here is an example of how to do this:
<input ng-model="showFreeEvents" type="checkbox" ng-change="onShowFreeEventsChanged()" />
<div ng-controller="myCtrl">
<div ng-repeat="event in filteredEvents">
<span>{{event.eventName}}</span></br>
<span>{{event.eventStartDateTime}}</span></br>
<span>{{event.itemCreatedDateTime}}</span></br>
</br></br>
</div>
</div>
Then in your controller:
$scope.showFreeEvents = false;
$scope.events = [ /* here you should store unfiltered events */ ];
$scope.filteredEvents = filterEvents($scope.events);
// whenever showFreeEvents checkbox value changes, re-filter the events
$scope.onShowFreeEventsChanged = function() {
$scope.filteredEvents = filterEvents($scope.events);
};
function filterEvents(events) {
return events.filter(function(event) {
// Here you should write your filtering logic.
// I'd recommend to remove such comparisons, as these are prone to errors.
// \
return !$scope.showFreeEvents || event.eventName === 'Event 9';
});
}

How do I retrieve values from checkboxes in JavaScript, using onchange to trigger a function?

I'm a High School student who takes a programming course (JavaScript) at school. We just had a test (which I miserably failed), but we are allowed to try again.
I have a couple of checkboxes. They all have an onchange which triggers a function later. I want to retrieve their values when I click on the checkboxes.
I've browsed around here a bit and seen something called jQuery. I have no idea what that is, so I would highly appreciate to get my help in pure JavaScript.
Okay, here is what I have of code. Note: Some variables and such are in Norwegian. I don't think it should be a problem, since I show the references to all.
My inputs (checkboxes):
<input type="checkbox" class="tur" value="0" onchange="funcSjekkBoks(this)">
<input type="checkbox" class="tur" value="1" onchange="funcSjekkBoks(this)">
<input type="checkbox" class="tur" value="2" onchange="funcSjekkBoks(this)">
<input type="checkbox" class="tur" value="3" onchange="funcSjekkBoks(this)">
<input type="checkbox" class="tur" value="4" onchange="funcSjekkBoks(this)">
I only need their value to be numbers, since I will use those in reference to an array list I have later.
Here is my function:
var inputTur = document.getElementsByClassName("tur");
console.log(inputTur);
function funcSjekkBoks(checkboxEl) {
var resultatListe = [];
if (checkboxEl.checked) {
resultatListe.push(inputTur.value);
console.log(resultatListe);
}
else {
console.log("usant")
}
}
What I would like to happen (if all checkboxes are checked from top to bottom):
resultatListe = [0, 1, 2, 3, 4]
When I uncheck a checkbox, it's value will be removed from the array.
Here is what currently happens:
When I check a checkbox I get [undefined] in my console, when I uncheck a checkbox I get usant (although that is the expected response, I haven't worked with the else part of my if-sentence yet.)
Below code will work for you:
var resultatListe = [];
function funcSjekkBoks(checkboxEl) {
var value = parseInt(checkboxEl.value);
if (checkboxEl.checked) {
resultatListe.push(value);
console.log(resultatListe);
}
else {
console.log("usant");
var indexToRemove = resultatListe.indexOf(value);
resultatListe.splice(indexToRemove,1);
}
}
You need to keep the array resultatListe outside the function other it will be initialized to empty everytime a checkbox is checked/un-checked, triggering the onchange handler. You were getting undefined as you were accessing 'value' property on HTMLCollection object which does not contain that property. Read more about it on MDN
var inputTur = document.getElementsByClassName("tur");
var resultatListe = [];
console.log(inputTur);
function funcSjekkBoks(checkboxEl) {
if (checkboxEl.checked) {
resultatListe.push(parseInt(checkboxEl.value));
}
else {
resultatListe = resultatListe.filter(d => d != checkboxEl.value)
}
console.log(resultatListe);
}
There were 2 mistakes in your logic:
1) You need to define resultatListe outside the function so that it won't get initialized to an empty array everytime
2) In you code resultatListe.push(inputTur.value); inputTur is the HTMLCollection of checkboxes whereas you need the single checkbox.
For the else logic, if the value of each checkbox is going to be unique you can use array.prototype.filter method to filter out the value of checkbox from resultatListe

Best way to detect changes when values might not exist anymore?

I've been trying to detect changes in multiple inputs on a web page.
To do that, I used a query like this:
$(.InputClass).data("InitialValues",$(.InputClass).serialize())
(I'm not in front of my code sadly but it should look like this)
Then later I compared the values in .data with the new values and it worked perfectly fine but for one single thing, a GridGiew.
In that GridView, the user can add or remove rows dynamically (adding or removing data). If I save the initial values in the .data, it will be destroyed with the row and both will be undefined (initial and new values). The input I need to check is hidden and the unique value can be accessed using $(.myNewClass).val() (as I tried to use a different class for this specific hidden input)
I was wondering what woudld be the best solution.
I tried to concatenate all val() from myNewClass using something like
var initialValues = $(.myNewClass).map(Function(x){
return x.val()
})
(Again, I am not in fron of my computer, and I am new to javascript and jquery).
It was not working. Intellisense could not see .map (and it crashed).
If there is no better way, could you help me with the way I record the concatenation of my val() values?
If there is a better way, could you please point me in the right direction?
Thank you very much!
At
var initialValues = $(.myNewClass).map(Function(x){
return x.val()
})
.myNewClass should be a String , within quotes $(".myNewClass") .
F at .map() callback should be lowercase f , to prevent calling native Function .
x at first parameter of .map(x) would be the index of the element or object within the collection of elements or objects - not the element ; try adjusting to .map() callback function parameters to .map(function(index, elem)) to correspond to their values within loop.
x.val() within .map() would return error , as x would be the DOM element <input> , not the jQuery object $(x) ; try utilizing x.value , or el.value to retrieve value of current element within loop
Try opening console , clicking "Run code snippet" twice at stacksnippets below . The alert does not appear to be called at stacksnippets, though the error message displays the contents of items at console
// create `items` object ,
// containing `initialValues` , `currentValues` properties,
// set initially to `undefined` ; set to `Array`
// at `load` , `unload` events
var items = {
"initialValues": undefined,
"currentValues": undefined
};
$(window)
.on({
"load": function() {
// set `items.initialValues` array
items.initialValues = $(".myNewClass").map(function(index, elem) {
return elem.value
}).toArray();
console.log("load", items);
},
"unload": function() {
// set `items.currentValues` array
items.currentValues = $(".myNewClass").map(function(index, elem) {
return elem.value
}).toArray();
console.log("unload", items);
alert(JSON.stringify(items, null, 4));
}
});
$(function() {
setTimeout(function() {
// do stuff
// remove first `.myNewClass` element "row"
$(".myNewClass").first().remove();
// change element at index 3 within `.myNewClass` collection
$(".myNewClass").eq(3).val(123);
}, 1500);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js">
</script>
<input type="hidden" value="1" class="myNewClass" />
<input type="hidden" value="2" class="myNewClass" />
<input type="hidden" value="3" class="myNewClass" />
<input type="hidden" value="4" class="myNewClass" />
<input type="hidden" value="5" class="myNewClass" />
See .map() , .toArray()

KnockoutJS Bind checkbox visibility to checkbox being checked OR having a certain value

So I have a checkbox, and I'm trying to implement the following logic to set the visibility:
If checkbox is checked OR the checkbox's value is below a specified number, set visible = true.
If the value exceeds the test value AND the checkbox is not checked, hide it.
Here is what I have so far:
<input type="checkbox" data-bind="visible: $data.Cost <= $root.itemLevel() - $root.totalEnchantLevelsUsed() || checked" />
I have tried several variations of getting 'checked', including changing 'checked' to $root.isChecked:
this.isChecked = ko.computed ( function (item) {
console.log('item', item); // PURELY TO TEST THE VALUE
}
But that is telling me that 'item' is undefined. When I try to explicitly pass in $data, I get an error message about ko.computed and having to set 'write' access.
Is there not a relatively simple way to do this that I'm just overlooking? Admittedly I'm not super familiar with knockout.
Here is something similar to what you're trying to do: http://jsfiddle.net/2aXrJ
Html:
<div data-bind="foreach:items">
<label data-bind="visible: isAllowedInWorkflow">
<input data-bind="value: val" type="checkbox" />
This checkbox has value
<span data-bind="text:val"></span>
</label>
</div>
jS:
ko.applyBindings({
items: [createItem(10), createItem(20), createItem(30) ]
})
function createItem(val) {
var _item = {
val: val
,isSelected: ko.observable(false)
};
_item.isAllowedInWorkflow = ko.computed(function() {
//notice the order is importeant since you always want isSelected to be triggered for the
//computed to calculate its dependencies
return !_item.isSelected() && val > 10;
});
return _item;
}

checkbox array in knockout being all checked on click

I am having an issue with knockout,
when i check a box, they're all being checked...
this is what I have:
_Categories_List has all the items,
and
My_categories is the empty list where I want to have each id added
this is the code:
<!-- ko foreach: _Categories_List -->
<input type="checkbox" data-bind="attr: {value: $data}, checked: $root.My_categories" />
<span data-bind="text: CODE"></span><br />
<!-- /ko -->
and this is the JS part of the code (i cant really change this as to how the code is in the documentation because i'm building off someone else's work and should use the same code - referring to the mapping.fromJS):
var Poi = new Object();
Poi.My_categories = [];
var _Poi = ko.mapping.fromJS(Poi);
var Categories_List = [];
var _Categories_List = ko.mapping.fromJS(Categories_List);
$(document).ready
(
function () {
ko.applyBindings(_Poi);
// here there's an ajax function to load the categories returned in i_Input.My_Result, then:
ko.mapping.fromJS(i_Input.My_Result, _Categories_List);
}
);
this is what the object loaded from ajax looks like:
{"My_Result":[
{"CODE":"chalet","DEF_POIS_CATEGORY_ID":2,"DESCRIPTION":"chalet","ENTRY_DATE":"2012-10-10","ENTRY_USER_ID":2,"OWNER_ID":1},
{"CODE":"vila","DEF_POIS_CATEGORY_ID":3,"DESCRIPTION":"villa","ENTRY_DATE":"2012-10-10","ENTRY_USER_ID":2,"OWNER_ID":1}
]}
The checked binding works off of the value of the input element. In your code, you are setting the value equal to an object, which turns into [object Object], so both of your inputs have the same value, which is why checking one toggles both.
So, you would want to set your value equal to a key on the object like your CODE property. If necessary, then you can use a computed observable to represent the actual objects.
Here is a sample: http://jsfiddle.net/rniemeyer/7n9gR/

Categories

Resources