How to have one checkbox checked by default angularjs - javascript

How can I have one checkbox checked by default when the page loads between two toggling check boxes. my code:
jsfiddle: http://jsfiddle.net/Lvc0u55v/456/
function MyCtrl($scope) {
$scope.changeAxis1 = function() {
if ($scope.thirtyDay) {
$scope.wholeTimeline = false;
}
};
$scope.changeAxis2 = function() {
if($scope.wholeTimeline) {
$scope.thirtyDay = false;
}
};
};
view
<label class='checkboxes' id='checkbox_1'>
<input type="checkbox" ng-model="thirtyDay" ng-change="changeAxis1()">
Two
</label>
<label class='checkboxes' id='checkbox_2'>
<input type="checkbox" ng-model="wholeTimeline" ng-change="changeAxis2()">
One
</label>

Initialize one of the values to true in your controller:
function MyCtrl($scope) {
$scope.changeAxis1 = function() {
if ($scope.thirtyDay) {
$scope.wholeTimeline = false;
}
};
$scope.changeAxis2 = function() {
if($scope.wholeTimeline) {
$scope.thirtyDay = false;
}
};
$scope.thirtyDay = true;
};
You also need to have ng-app and ng-controller in your view in order for Angular to do anything:
<div class="checkbox" ng-app="" ng-controller="MyCtrl">
http://jsfiddle.net/Lvc0u55v/457/

You can use ng-checked="expression"
<input type="checkbox" ng-checked="expression" ng-model="thirtyDay" ng-change="changeAxis1()">
Two
and put some logic for expression how you want the checkbox to be checked

Related

how to iterate through checkbox object

I have three checkboxes:-
<label>Type:</label>
<label>one</label>
<input type="checkbox" name="type" ng-model="a.Type[0]"/>
<label>two</label>
<input type="checkbox" name="type" ng-model="a.Type[1]"/>
<label>three</label>
<input type="checkbox" name="type" ng-model="a.Type[2]"/>
These checkboxes are stored in the backend as an array of string.
My value is displaying in:-
<li class="list-group-item"><strong>Type</strong>: <span ng-repeat="values in myArray">{{values}}</span></li>
My directive code is:-
(function () {
'use strict';
angular.module('myApp.components')
.directive('abc', abc);
abc.$inject = ['$http', '$timeout', 'ApiServices'];
function abc($http, $timeout, ApiServices) {
return {
restrict: 'EA',
scope: {
},
link: function (scope, el, attrs) {
scope.a = {};
$('#abc').on('hide.bs.modal', function () {
scope.active = false;
});
$('#abc').on('shown.bs.modal', function () {
scope.active = true;
scope.myArray = [];
scope.iterate = function () {
for (var key in scope.a.Type) {
if (scope.a.Type.hasOwnProperty(key)) {
scope.myArray.push(scope.a.Type[key]);
}
}
};
scope.iterate();
},
templateUrl: ''
};
}
})();
Here what I am trying to do is- I want to iterate through 'Type' checkboxes and pushed the values in 'myArray', and then display only the values.
Probably, my example below is somewhat similar to what you are looking for:
HTML:
<span>Select Type:</span>
<div ng-repeat="type in myArray">
<input type="checkbox" ng-model="type.value" /> {{type.type}}
</div>
<span>Selected Types:</span>
<div ng-repeat="type in myArray">
<span ng-show="type.value"> {{type.type}}</span>
</div>
JS:
$scope.a = {};
$scope.a.Type = ["One","Two","Three"]; // your string array
$scope.myArray = [];
$scope.a.Type.forEach(function(item){
$scope.myArray.push({type: item, value: false }); // create new array to make it selectable via checkbox
});
I guess, you no more need your directive now. The iteration and filtering is done in HTML itself.
I hope this helps.

How to change CSS in Controller

I m trying to do a workaround for a bug. i need to just change the css of an element when an other checkbox is clicked. But it is not working.. It just works when i click on an other button somewhere else but when i click on the checkbox the view is not being refreshed maybe ?
Any ideas ?
View:
<input
type="checkbox"
value="application.callback" id="telefonBox"
ng-click="application.callback = !application.callback; toggleClass(application.callback)"
/>
Controller:
$scope.toggleClass = function(newValue) {
var element = angular.element(document.querySelector('#additional'));
if (newValue) {
element.toggleClass("tooltip-agent tooltip-agentChecked ");
} else {
element.toggleClass("tooltip-agentChecked tooltip-agent");
}
$scope.$apply();
}
i tried this to but not working
$scope.$watch('$scope.application.callback', function (newValue, oldValue) {
var element = angular.element(document.querySelector('#additional'));
if (newValue) {
element.toggleClass("tooltip-agent tooltip-agentChecked ");
} else {
element.toggleClass("tooltip-agentChecked tooltip-agent ");
}
add ng-modal into checkbox
<input type="checkbox" ng-model="application.callback">
and ng-class into your #additional element
<div id="additional" ng-class="{true:'tooltip-agent tooltip-agentChecked', false:'tooltip-agentChecked tooltip-agent'}[application.callback]"></div>
DEMO
You should not manipulate elements in angular as much as possible, you can do it easier with ng-class like this
<div id="test" ng-class='{ active: vm.isChecked }'>
lorem
</div>
ng-class accepts an object as parameter, in this case it's { active: vm.isChecked } which mean if vm.isChecked evaluates to true, the active class will be applied to the element
$scope.selection = function($event) {
var checkbox = $event.target;
var action = (checkbox.checked ? 'check' : 'uncheck');
if(action == "check")
angular.element(document.querySelector('#additional')).addClass("tooltip-agent tooltip-agentChecked");
else
angular.element(document.querySelector('#additional')).addClass("tooltip-agentChecked tooltip-agen");
};
});
<input type="checkbox" id="additional" ng-model="check" ng-click="selection($event)" >

Push data on array when checkbox is checked and remove data when checkbox is unchecked

I am taking data from table and display as multi check checkboxes.My checkboxes when checked pushes data on array for that particular checkbox.But when unchecked ,the respective data should be removed from the array.How can I achieve this?
HTML:
<div ng-repeat="data in filters.status" >
<label class="Form-label--tick">
<input type="checkbox" value="data.id" id="status" ng-model="status" class="Form-label-checkbox" ng-change="IfCheck(data.id,status)" >
<span class="Form-label-text"> {{data.status}}</span>
</label>
</div>
Javascript:
<script>
$scope.IfCheck = function (data, check) {
if (check) {
status.push(data);
$scope.checkedData[0].status = status;
}
else {
var index = $scope.status.indexOf(data);
$scope.status.splice(index);
}
};
</script>
This can be written as like this:
var app = angular.module('sa', []);
app.controller('FooCtrl', function($scope) {
$scope.ids = [];
$scope.filters = [{
id: 1,
status: false
}, {
id: 2,
status: false
}, {
id: 3,
status: false
}]
$scope.IfCheck = function(id, check) {
if (check) {
$scope.ids.push(id);
} else {
var index = $scope.ids.indexOf(id);
$scope.ids.splice(index, 1);
}
};
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="sa" ng-controller="FooCtrl">
<div ng-repeat="data in filters">
<label class="Form-label--tick">
<input type="checkbox" value="data.id" id="status" ng-model="data.status" class="Form-label-checkbox" ng-change="IfCheck(data.id, data.status)">
<span class="Form-label-text"> {{data.status}}</span>
</label>
</div>
Selected ids: {{ids}}
</div>
You can utilize the ng-model to see if the input is checked or unchecked. Note that I simplified the code, so you will need to add in your various attributes and logic to what's below:
HTML:
<input type="checkbox" ng-model="isChecked" ng-change="IfCheck()">
JS:
$scope.isChecked = false;
$scope.IfCheck = function () {
if ($scope.isChecked === true) {
// checked
} else {
// unchecked
}
};
This is the example plnkr for a checkbox input with ng-model that is on the Angular documentation.
For multiple checkboxes, you will need to track something like isChecked for each checkbox.

Optimizing js -Saving values from checkboxes in object

i'm rather new to js and i'd like to optimize my code.
I have a group of checkboxes and their boolean values are saved in an object for further calculations.
HTML:
<fieldset>
<input type="checkbox" id="checkbox1" onchange="checkbox1Changed()" value="checkbox1">
<input type="checkbox" id="checkbox2" onchange="checkbox2Changed()" value="checkbox2">
<input type="checkbox" id="checkbox3" onchange="checkbox3Changed()" value="checkbox3">
</fieldset>
JS:
//store values for further computation
var boxValues = {
box1: false,
box2: false,
box3: false,
}
//get checkboxvalues from view
var checkbox1 = document.getElementById("checkbox1");
var checkbox2 = document.getElementById("checkbox2");
var checkbox3 = document.getElementById("checkbox3");
//update values in boxValues
function checkbox1Changed() {
if (checkbox1.checked) {
boxValues.box1 = true;
} else {
boxValues.box1 = false;
}
}
function checkbox2Changed() {
if (checkbox2.checked) {
boxValues.box2 = true;
} else {
boxValues.box2 = false;
}
}
function checkbox3Changed() {
if (checkbox3.checked) {
boxValues.box3 = true;
} else {
boxValues.box3 = false;
}
}
Since i plan on having approximately 20 checkboxes in the view there would be a lot of repeating code.
Does anyone know a smarter way to do that?
Thanks in advance!
Vin
Add common class to all the checkboxes
Create an object for the values of all checkboxes
Bind event handler on the checkboxes using the common class
Update the status of clicked checkbox in event handler
Also, it is good practice to bind events in javascript instead of inline in the HTML.
var myObj = {
checkbox1: false,
checkbox2: false,
checkbox3: false
};
$('.myCheckbox').on('change', function() {
var thisId = $(this).attr('id');
myObj[thisId] = this.checked;
console.log(myObj);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.0/jquery.min.js"></script>
<fieldset>
<input type="checkbox" id="checkbox1" value="checkbox1" class="myCheckbox">
<input type="checkbox" id="checkbox2" value="checkbox2" class="myCheckbox">
<input type="checkbox" id="checkbox3" value="checkbox3" class="myCheckbox">
</fieldset>
You can bind the same function to every checkbox, and use the id of the checkbox as the key in your object:
function onCheckBoxChanged(e){
var sender = e.target;
boxValues[sender.id] = (sender.checked);
}
Playing around with this should save you a lot of typing :)

knockoutjs radio button checked value with protectedobservable

thank you for looking into this.
I have the following example built: http://jsfiddle.net/zm381qjx/5/
This is a menu list builder. When you add a menu, an edit form pops up. Using protectedObservable so that i can either commit or reset (as per code). One functionality, which i am having problems with, is there is radio button list (for TypeId), and depending on the value (10 = Url, 20 = Category, 30 = Page), you set the respective properties (10 = Url, 20 = CategoryId, 30 = PageId).
Flicking through the radio buttons, if Url is selected, another textbox should show (based on urlVisible) so user can enter the Url. I have added a span with text: TypeId.temp so i can see the temporary value. This is very irregular. Try to flick through several times.
Any help will be greatly appreciated.
My HTML
<a class="btn btn-primary" data-bind="click: addMenu">Add Menu</a>
<ul data-bind="foreach: Menus">
<li></li>
</ul>
<div class="panel panel-default" data-bind="slideIn: editMenuItem, with: editMenuItem">
<div class="panel-body">
<div class="form-group">
<label for="MenuName">Name: </label>
<input type="text" id="MenuName" data-bind="value: Name" class="form-control" />
</div>
<label class="radio-inline">
<input type="radio" name="MenuTypeId" value="10" data-bind="checked: TypeId" /> Url
</label>
<label class="radio-inline">
<input type="radio" name="MenuTypeId" value="20" data-bind="checked: TypeId" /> Category
</label>
<label class="radio-inline">
<input type="radio" name="MenuTypeId" value="30" data-bind="checked: TypeId" /> Page
</label>
<div class="form-group" data-bind="visible: urlVisible">
<label for="MenuUrl">Url: </label>
<input type="text" id="MenuUrl" data-bind="value: Url" class="form-control" />
</div>
<br />
<p>TypeId.temp = <span data-bind="text: TypeId.temp"></span></p>
<br /><br />
<input type="button" class="btn btn-success" value="Update" data-bind="click: commit" /> or
Cancel
</div>
</div>
My JS:
var vm = null;
//wrapper for an observable that protects value until committed
ko.protectedObservable = function (initialValue) {
//private variables
var _temp = ko.observable(initialValue);
var _actual = ko.observable(initialValue);
var result = ko.dependentObservable({
read: function () {
return _actual();
},
write: function (newValue) {
_temp(newValue);
}
});
//commit the temporary value to our observable, if it is different
result.commit = function () {
var temp = _temp();
if (temp !== _actual()) {
_actual(temp);
}
};
//notify subscribers to update their value with the original
result.reset = function () {
_actual.valueHasMutated();
_temp(_actual());
};
result.temp = _temp;
return result;
};
ko.bindingHandlers.slideIn = {
init: function (element) {
$(element).hide();
},
update: function (element, valueAccessor) {
var value = ko.utils.unwrapObservable(valueAccessor());
if (value) {
$(element).stop().hide().slideDown('fast');
} else {
$(element).stop().slideUp('fast');
}
}
};
var Menu = function (Id, Name, TypeId, CategoryId, PageId, Url) {
var self = this;
/* Core Properties */
self.Id = ko.observable(Id);
self.Name = ko.protectedObservable(Name);
self.TypeId = ko.protectedObservable(TypeId);
self.CategoryId = ko.protectedObservable(CategoryId);
self.PageId = ko.protectedObservable(PageId);
self.Url = ko.protectedObservable(Url);
/* Virtual Properties */
self.urlVisible = ko.computed(function () {
return self.TypeId.temp() == "10";
}, self);
/* Virtual Functions */
self.editMenu = function (data) {
if(vm.editMenuItem()) {
vm.editMenuItem(null);
}
vm.editMenuItem(data);
};
/* Core Functions */
self.commit = function () {
if (self.Name.temp() == '' || self.Name.temp() == null) {
alert('Please enter a name.'); return;
}
self.Name.commit();
self.TypeId.commit();
self.CategoryId.commit();
self.PageId.commit();
self.Url.commit();
vm.editMenuItem(null);
};
self.reset = function () {
self.Name.reset();
self.TypeId.reset();
self.CategoryId.reset();
self.PageId.reset();
self.Url.reset();
vm.editMenuItem(null);
};
};
var ViewModel = function() {
var self = this;
/* Core Properties */
self.Menus = ko.observableArray([]);
/* Virtual Properties */
self.editMenuItem = ko.observable(null);
self.addMenu = function(){
var menu = new Menu(0, "New Menu", "10", 0, 0, "");
self.Menus.push(menu);
self.editMenuItem(menu);
};
};
$(function () {
vm = new ViewModel();
ko.applyBindings(vm);
});
If you change your radio button binding to
<input type="radio" name="MenuTypeId" value="10" data-bind="checked: TypeId.temp" />
The temp id will be changed accordingly and radio button behaviour is consistent, but not with TypeId as value.
also the protectedObservable binding the radio button value is not playing nice
When you manually click the radio the TypeId value is never changed (as you are not committing the value) and I guess that as the radio button value never changes from 10 , it is not recognizing the subsequent manual clicks on Url radio button.
I updated the value using a button and it is changing accordingly; but then it will not move the value from that TypeId on subsequent radio button clicks
And the problem is still appearing for protectedObservable binding but not with a simple observable.
Code which explores this idea further: http://jsfiddle.net/zm381qjx/101/

Categories