Since I am using Semantic UI for checkboxes, the <input> tag is wrapped with a <div class="ui checkbox"> and what happens is when the box is checked, it just adds the class checked.
<div class="field" ng-repeat="animal in animals">
<div class="ui checkbox">
<input class="hidden" tabindex="0" type="checkbox" value="{{animal.id}}" ng-model="animal.selected">
<label>{{animal.name}}</label>
</div>
</div>
How do I get the id or value of the selected checkboxes using AngularJS? Thank you.
You can have a function in your controller
$scope.getAnimal= function(){
angular.forEach($scope.animals, function(animal){
if (animal.selected) do smth here...
})
}
You can use Array.prototype.filter() method to get only the selected objects.
Here's a demonstration:
angular.module('app', [])
.controller('mainCtrl', function($scope) {
$scope.animals = [];
for (var i = 0; i <= 5; i++) {
$scope.animals.push({
"id": Math.floor(Math.random() * 310),
"name": "Name " + Math.floor(Math.random() * 420),
"selected": i % 2 === 0 ? true : false
});
}
$scope.selected = [];
$scope.show = function() {
$scope.selected = $scope.animals.filter(function(value) {
return value.selected;
});
}
});
<html ng-app="app">
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.7/angular.min.js"></script>
</head>
<body ng-controller="mainCtrl">
<div class="field" ng-repeat="animal in animals track by $index">
<div class="ui checkbox">
<input id="checkbox{{$index}}" class="hidden" tabindex="0" type="checkbox" value="{{animal.id}}" ng-model="animal.selected">
<label for="checkbox{{$index}}" ng-bind="animal.name"></label>
</div>
</div>
<hr>
<button type="button" value="show" ng-click="show()">Show selected tems</button>
<pre ng-bind="selected | json"></pre>
</body>
</html>
Related
I have below code where I am displaying buttons based on array values. I want to select button based on a condition which checks if it matches with another array values. I have added an ng-class to check i in array1 loop matches listApi but couldn't come up with correct logic and get it tow work. Need help please
<label ng-repeat="i inn array1 track by $index">
<label class="btn-primary" ng-click="array1Selection()">
<span ng-class="{'btn-primary': i.name === listApi[0].name}"></span>
{{i.name}}
</label>
</div>
</label>
Your span tag is empty and I think you should put {{i.name}} inside that. also you should not add class 'btn ...' to your label. Hope this code helps you.
var app = angular.module("app", []);
app.controller("MainCtrl", function($scope) {
$scope.array1 = [{
id: 1,
name: "abc"
}, {
id: 1,
name: "xyz"
}];
$scope.listApi = [{
id: 2,
name: "xyz"
}];
$scope.existInList = function(itm) {
let x = $scope.listApi.findIndex(it => {
return it.name == itm.name
});
return x == -1 ? false : true;
}
});
.exists {
color: green
}
.noexists {
color: red
}
<html ng-app="app">
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
</head>
<body ng-controller="MainCtrl">
<h2>Add class to existing items and others</h2>
<label ng-repeat="i in array1">
<div data-toggle="buttons">
<label>
<div class="itemcontent">
<input type="checkbox" name="array1Select" />
<span ng-class="{true: 'exists', false: 'noexists'}[existInList(i) === true]">
{{i.name}}
</span>
</div>
</label>
</div>
</label>
<h2>Show only if exists in list</h2>
<label ng-repeat="i in array1">
<div data-toggle="buttons">
<label ng-if="existInList(i)">
<div class="itemcontent">
<input type="checkbox" name="array1Select" />
<span>
{{i.name}}
</span>
</div>
</label>
</div>
</label>
</body>
</html>
I'm not 100% sure JS' find will work inline in Angular but is so...
<label ng-repeat="i inn array1 track by $index">
<div data-toggle="buttons">
<label class="btn btn-w-m btn-primary" ng-click="array1Selection()">
<div class="itemcontent">
<input type="checkbox" name="array1Select" />
<span nng-class="btn btn-w-m btn-primary: listApi.find(a => a.name === i.name)"></span>
{{i.name}}
</div>
</label>
</div>
</label>
A simple modification
var app = angular.module("app", []);
app.controller("MainCtrl", function($scope) {
$scope.array1 = [{ id: 1, name: "abc" }, { id: 1, name: "xyz"
}];
$scope.listApi = [{ id: 2, name: "xyz" }];
$scope.foundInApiList = function(name) {
for(var i = 0; i < $scope.listApi.length; i++)
if($scope.listApi[i].name == name)
return true;
return false;
}
});
.exists {
color: green
}
.noexists {
color: red
}
<html ng-app="app">
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
</head>
<body ng-controller="MainCtrl">
<label ng-repeat="i in array1 track by $index">
<div data-toggle="buttons">
<label class="btn btn-w-m btn-primary" ng-click="array1Selection()">
<div class="itemcontent">
<input type="checkbox" name="array1Select" />
<span class="btn btn-w-m btn-primary" ng-class="{true: 'exists', false: 'noexists'}[foundInApiList(i.name)]">{{i.name}}</span>
</div>
</label>
</div>
</label>
</body>
</html>
I'm using AngularJs & Javascript for my very first application. I'm triying to show info from an API as a checkbox. Right now it's working, but, how can i validate if any of the checkbox options are checked with a submit button?
I was searching here in stackoverflow and find a way, but it's working only with the last option. Here's a part of my html:
<form name="imtesting" ng-submit="imtesting.$valid && validate()" ng-show="$ctrl.coupons.length > 0">
<ul>
<li ng-repeat="c in $ctrl.coupons">
<input type="checkbox"
name="couponBox"
ng-checked="c.Select"
ng-click="$ctrl.selectOne(c)"
ng-model="formData.couponBox" required/>{{c.CodeCoupon}}
<br>
</li>
</ul>
<span ng-show="submitted == true && imtesting.couponBox.$error.required">Select at least one cupon!</span></form>
And the button:
<button type="submit" ng-click="submitted = true">Save</button>
Hope you can help me. It's a new world for me this job.
Thanx in advance.
Well, why not create a validation function on your Controller.
Loop over all your coupon objects and check if they have a value.
e.g
$scope.requireCoupon = function() {
var nrCouponsChecked = 0;
$ctrl.coupons.forEach(function(coupon) {
if (coupon.Select) {
nrCouponsChecked++;
}
});
}
// and in your template you would use it like
<span ng-show="submitted == true && requireCoupon()">Select at least one cupon!</span>
That is because you are using the same ng-model for all the checkboxes by doing this:
ng-model="formData.couponBox"
The previous code sets an ng-model (formData.couponBox) for all of the checkboxes.
A valid option would be create an object which will contains the ng-model of every checkbox, like this (Demo with some fake data)
angular
.module('app', [])
.controller("myCtrl", function() {
var wizard = this;
wizard.$ctrl = {
//fake data
coupons: [{
Select: false,
CodeCoupon: "1st"
}, {
Select: false,
CodeCoupon: "2nd"
}],
//create an object for storing the checkbox models
checkBoxModels: {},
checkIfAnyChecked: checkIfAnyChecked
}
return wizard.$ctrl;
function checkIfAnyChecked() {
for (var k in wizard.$ctrl.checkBoxModels) {
if (wizard.$ctrl.checkBoxModels.hasOwnProperty(k) && wizard.$ctrl.checkBoxModels[k]) {
//for instance, if 3rd checkbox is checked, wizard.$ctrl.checkBoxModels will be {3: true} and so on...
return true;
}
}
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.4.8/angular.js"></script>
<div ng-app="app" ng-controller="myCtrl as ctrl">
<ul>
<li ng-repeat="c in ctrl.coupons">
<input type="checkbox" name="couponBox" ng-checked="c.Select" ng-click="ctrl.selectOne(c)" ng-model="ctrl.checkBoxModels[$index]" required/>{{c.CodeCoupon}}
<br>
</li>
</ul>
<span ng-show="submitted == true && !ctrl.checkIfAnyChecked()">Select at least one cupon!</span>
<br />
<button type="submit" ng-click="submitted = true">Save</button>
</div>
You have to create dynamic names for each checkbox input to do validations.
Here is an example since you have not provided the dataset.
var app=angular.module("App",[]);
app.controller("AppCtrl",function($scope){
var selectedFruits = {
Mango: true
};
var calculateSomeSelected = function() {
$scope.someSelected = Object.keys(selectedFruits).some(function (key) {
return selectedFruits[key];
});
};
$scope.formData = {
selectedFruits: selectedFruits
};
$scope.fruits = [{'name':'Apple'}, {'name':'Orange'}, {'name':'Banana'}, {'name':'Mango'}];
$scope.checkboxChanged = calculateSomeSelected;
calculateSomeSelected();
});
<!DOCTYPE html>
<html ng-app="App">
<head>
<meta charset="utf-8" />
<script data-require="angular.js#1.4.9" data-semver="1.4.9" src="https://code.angularjs.org/1.4.9/angular.js"></script>
<script src="script.js"></script>
</head>
<body>
<div ng-controller="AppCtrl">
<form class="Scroller-Container" name="multipleCheckbox" novalidate="" ng-submit="submitForm()">
<h3>What would you like?</h3>
<div ng-repeat="fruit in fruits">
<input type="checkbox" ng-model="formData.selectedFruits[fruit.name]" ng-change="checkboxChanged()" ng-required="true" name="fruits_{{$index}}" /> {{fruit.name}}
<p style="color: red;" ng-show="multipleCheckbox.$submitted&&multipleCheckbox.fruits_{{$index}}.$error.required">You must choose {{fruits[$index].name}} fruit</p>
</div>
<input type="submit" value="Submit">
</form>
<pre>Fruits model:
{{formData.selectedFruits | json}}</pre>
</div>
</body>
</html>
I'm trying to create a list where there are multiple select all buttons to for ng-repeat check boxes.
HTML code
<div class="col-xs-12"ng-repeat="items in testArray">
<div class="col-xs-6">
{{items.brand}}
</div>
<div class="col-xs-6 col-sm-offset-6">
<button ng-click="selectAll()">select All</button>
<div ng-repeat="i in items.form">
<input type="checkbox"/>{{i.formName}}
</div>
</div>
</div>
you can try it.this example you can manipulate it according to your need
https://plnkr.co/edit/qD7CABUF9GLoFCb8vDuO?p=preview
$scope.test=function(event){
if(event.currentTarget.checked==true)
{
var togglestatus=$scope.isAllSelected;
angular.forEach($scope.options,function(object){
object.selected=togglestatus
})
}else{
angular.forEach($scope.options,function(object){
object.selected=false
})
}
}
html:
<body ng-app="test" ng-controller="testctrl">
<label>
<input type="checkbox" ng-model="isAllSelected" ng-click="test($event)">SelectAll</label>
<div ng-repeat="option in options">
<input type="checkbox" ng-model="option.selected">checkbox</div>
</body>
Please check ngChecked directive. You need to add it to your input
<input type="checkbox" ng-checked="i.isChecked" />
and then in selectAll() method set isChecked property on every item to true.
look at code snippet given below , this will give you idea.
var app = angular.module("myApp",[]);
app.controller('demoCtrl',function($scope){
$scope.itemsArray = [{name:"Test 1",forms:[{formName:"xyz 1 "},{formName:"xyz 1 "}]},{name:"Test 2",forms:[{formName:"xyz 2 "},{formName:"xyz 1 "}]},{name:"Test 3 ",forms:[{formName:"xyz 3"},{formName:"xyz 1 "}]}];
$scope.selectAll = function(item){
for(var i =0;i < item.forms.length;i++)
{
item.forms[i].isChecked = true;
}
}
$scope.removeAll = function(item) {
for(var i =0;i < item.forms.length;i++)
{
item.forms[i].isChecked = false;
}
}
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="myApp">
<div ng-controller="demoCtrl">
<div ng-repeat="item in itemsArray">
<span>{{item.name}}</span>
<button ng-click="selectAll(item)"> select All </button>
<button ng-click="removeAll(item)"> Deselect All </button>
<div ng-repeat="i in item.forms">
<input type="checkbox" ng-model="i.isChecked"/>
</div>
</div>
</div>
</div>
You can simply set a variable to true like this
ng-click="selectAll = true"
and then use the ng-checked directive to set the checkbox to checked when the expression inside is true
ng-checked="selectAll"
HTML
<div class="col-xs-12"ng-repeat="items in testArray">
<div class="col-xs-6">
{{items.brand}}
</div>
<div class="col-xs-6 col-sm-offset-6">
<button ng-click="selectAll = true">select All</button>
<div ng-repeat="i in items.form">
<input type="checkbox" ng-checked="selectAll"/>{{i.formName}}
</div>
</div>
</div>
Created a fiddle, showcasing your need for requirement "select all" - http://jsfiddle.net/deeptechtons/TKVH6/
//html
<div>
<ul ng-controller="checkboxController">
<li>Check All
<input type="checkbox" ng-model="selectedAll" ng-click="checkAll()" />
</li>
<li ng-repeat="item in Items">
<label>{{item.Name}}
<input type="checkbox" ng-model="item.Selected" />
</label>
</li>
</ul>
</div>
//js
angular.module("CheckAllModule", [])
.controller("checkboxController", function checkboxController($scope) {
$scope.Items = [{
Name: "Item one"
}, {
Name: "Item two"
}, {
Name: "Item three"
}];
$scope.checkAll = function () {
if ($scope.selectedAll) {
$scope.selectedAll = true;
} else {
$scope.selectedAll = false;
}
angular.forEach($scope.Items, function (item) {
item.Selected = $scope.selectedAll;
});
};
});
I'm kinda new in AngularJS and my issue is:
I have a loop like this:
<body ng-app="ngToggle">
<div ng-controller="AppCtrl">
<input type="checkbox" ng-repeat="btn in btns" class="here" value="{{btn.value}}">
<input type="text" class="uncheck" disabled>
</div>
</body>
One of those checkboxes has a value of "OTHER", and what I need to do is: when the checkbox with the "OTHER" value is checked it remove the disabled attribute from the <input type="text" class="uncheck" disabled>
This is my controller:
angular.module('ngToggle', [])
.controller('AppCtrl',['$scope', function($scope){
$scope.btns = [
{value:'one'},
{value:'two'},
{value:'other'}
];
}]);
Hope someone can help me,
Thanks.
Use ng-change directive and test value of other checkbox in forEach-loop
angular.module('ngToggle', [])
.controller('AppCtrl', ['$scope',
function($scope) {
$scope.disabled = true;
$scope.btns = [{
value: 'one'
}, {
value: 'two'
}, {
value: 'other'
}];
$scope.onChange = function() {
$scope.btns.forEach(function(btn) {
if (btn.value === 'other' && btn.status === true) {
$scope.disabled = false;
} else {
$scope.disabled = true;
}
});
}
}
]);
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<body ng-app="ngToggle">
<div ng-controller="AppCtrl">
<input type="checkbox" ng-repeat="btn in btns" class="here" ng-model='btn.status' ng-change='onChange()'>
<input type="text" class="uncheck" ng-disabled='disabled'>
</div>
</body>
try like this.
angular.module('ngToggle', [])
.controller('AppCtrl',['$scope', function($scope){
$scope.btns = [
{value:'one',name:"one"},
{value:'two',name:'two'},
{value:'other',name:'other'}
];
$scope.disable=true;
$scope.check = function(value){
if(value == "'other'")
$scope.disable = false;
else
$scope.disable=true;
}
}]);
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="ngToggle">
<div ng-controller="AppCtrl">
<div ng-repeat="btn in btns">
<input type="checkbox" ng-model="btn.value" ng-true-value="'{{btn.value}}'" ng-change="check(btn.value)" >{{btn.name}}
</div>
<input type="text" class="uncheck" ng-disabled='disable'>
</div>
</div>
Make use of ng-models. Please avoild using "values attribute" as well in AngularJS. The alternative for values is "ng-init". Well anyway, here is a working code:
<!DOCTYPE html>
<html >
<head>
<link rel="stylesheet" type="text/css" href="http://netdna.bootstrapcdn.com/bootstrap/3.1.1/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.9/angular.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.2/jquery.min.js"></script>
</head>
<body ng-app="ngToggle">
<div ng-controller="AppCtrl">
<p ng-repeat="btn in btns">
<input type="checkbox" ng-model="btn.bool" value="ss" class="here" > {{ btn.value }}
</p>
<input type="text" ng-model="textModel" class="uncheck" ng-disabled="other.bool">
<p>{{ other.bool }} -- {{textModel }}</p>
</div>
<script type="text/javascript">
angular.module('ngToggle', [])
.controller('AppCtrl',['$scope', function($scope){
$scope.btns = [
{value:'one', bool:false},
{value:'two', bool:true},
{value:'other', bool:true}
];
$scope.otherBool = $scope.btns[2]['bool'];
$scope.btns.map(function(obj){
//alert(JSON.stringify(obj))
if((obj.value) == 'other'){
$scope.other = obj;
}
});
}]);
</script>
</body>
</html>
YOu can check it in plunker as well: http://plnkr.co/edit/GODfWbhlWvzjLKHFcEYs?p=preview
How can we add a textbox element to a form dynamically using AngularJs. For example in this case, I have a text and textbox which I want to add one other of this pair by clicking on a button using AngularJs.
<div ng-app>
<div ng-controller="ClickToEditCtrl">
<div ng-hide="editorEnabled" ng-click="editorEnabled=true">
{{title}}
</div>
<div ng-show="editorEnabled">
<input ng-model="title">
<button href="#" ng-click="editorEnabled=false">Done editing</button>
</div>
</div>
</div>
<div>
<input type="text" placeholder="Enter answer">
</div>
I implemented it myself. You could dynamically add an element by using ng-repeat in a
<li ng-repeat="elemnt in questionelemnt">
Here it is the Demo: fiddle
js file
$scope.choices = [{id: 'choice1'}, {id: 'choice2'}, {id: 'choice3'}];
$scope.addNewChoice = function() {
var newItemNo = $scope.choices.length+1;
$scope.choices.push({'id':'choice' +newItemNo});
};
$scope.showAddChoice = function(choice) {
return choice.id === $scope.choices[$scope.choices.length-1].id;
};
html
<div class="form-group" data-ng-repeat="choice in choices">
<label for="choice" ng-show="showChoiceLabel(choice)">Choices</label>
<button ng-show="showAddChoice(choice)" ng-click="addNewChoice()">Add another choice</button>
<input type="text" ng-model="choice.name" name="" placeholder="Enter a restaurant name">
</div>
<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script>
<body>
<div ng-app="myApp" ng-controller="myCtrl">
<ol>
<li ng-repeat="element in elements">
<input type="text" ng-model="element.value"/>
</li>
</ol>
<br/>
<b>Click here to add Textbox:</b><br/><input type="button" value="New Item" ng-click="newItem()"/>
<br/>
<br/>
<b>Click here to see ng-model value:</b><br/>
<input type="button" value="submit" ng-click="show(elements)">
</div>
<script>
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
var counter=0;
$scope.elements = [ {id:counter, value : ''} ];
$scope.newItem = function(){
counter++;
$scope.elements.push( { id:counter,value:''} );
}
$scope.show=function(elements) {
alert(JSON.stringify(elements));
}
});
</script>
</body>
</html>