Angular Checkboxes “Select All” functionality not working - javascript

I have the code like this
HTML
<div class="check_toggle" ng-click="toggleAll(payout)">
select all
<input type="checkbox" aria-label="Art" ng-model="checkall"/>
</div>
<table>
<thead>
<tr>
<th>Week</th>
<th>Release Payment</th>
</tr>
</thead>
<tbody>
<tr ng-repeat="item in payout">
<td>{{item.value}}</td>
<td>
<div class="checkbox pay_check">
<input aria-label="Art" type="checkbox" ng-model="allCheckBox[$index]" ng-click="selectItem(item._id,selected,payout)">
</div>
</td>
</tr>
</tbody>
controller
$scope.payout= [
{'_id':1, value:'Option1'},
{'_id':2, value:'Option2'}
];
$scope.toggleAll = function(payout) {
$scope.checkall = !$scope.checkall;
for(var i=0;i<payout.length;i++){
if($scope.checkall===false){
$rootScope.selected=[];
$scope.allCheckBox[i] = $scope.checkall ;
}else{
$rootScope.selected[i]=payout[i]._id;
$scope.allCheckBox[i] =$scope.checkall ;
}
}
}
$scope.selectItem = function(id, list,payout) {
console.log('id',id);
var idx = list.indexOf(id);
if (idx > -1) {
list.splice(idx, 1);
} else {
list.push(id);
}
if(payout.length==$rootScope.selected.length){
$scope.checkall=true;
console.log($scope.checkall);
// $scope.checkall= $scope.checkall;
console.log('All checkboxes selected');
}
else{
$scope.checkall=false;
console.log('Not All checkboxes selected');
}
}
I have separate checkboxes using ng-repeat, and select all checkbox.First when i select all the individual select boxes, the checkall box will checked automatically as i expected and also check all also select all the individual checkboxes as i expected, but the issue is if i click checkall checkbox first and all individual items next, it will not work as i expected(the checkall checkbox will not be checked or un-checked based on selection).
i tried some stack overflow answers, but it is the same. Could anyone tell me how. please

The main problem here is that you are assigning ng-model to the "checkall" checkbox and a ng-click that calls a function in which you define the value of $scope.checkall again.
You don't need to do that, since ng-model already sets the value of that variable for you.
Check out this fiddle, with the same code you provided, but with the fix:
https://jsfiddle.net/h46rLzhs/5/
angular.module('MyApp',[])
.controller('MyController', function($rootScope, $scope){
$rootScope.selected=[];
$scope.allCheckBox=[];
$scope.payout= [
{'_id':1, value:'Option1'},
{'_id':2, value:'Option2'}
];
$scope.toggleAll = function(payout) {
// Line below is not needed
//$scope.checkall = !$scope.checkall;
for(var i in payout){
if($scope.checkall===false){
$rootScope.selected=[];
$scope.allCheckBox[i] = $scope.checkall ;
}else{
$rootScope.selected[i]=payout[i]._id;
$scope.allCheckBox[i] =$scope.checkall ;
}
}
}
$scope.selectItem = function(id, list,payout) {
console.log('id',id);
var idx = list.indexOf(id);
if (idx > -1) {
list.splice(idx, 1);
} else {
list.push(id);
}
if(payout.length==$rootScope.selected.length){
$scope.checkall=true;
console.log($scope.checkall);
// $scope.checkall= $scope.checkall;
console.log('All checkboxes selected');
}
else{
$scope.checkall=false;
console.log('Not All checkboxes selected');
}
}
})
<div ng-app="MyApp">
<div ng-controller="MyController">
<div ng-click="toggleAll(payout)">
select all
<input type="checkbox" ng-model="checkall"/>
</div>
<table>
<thead>
<tr>
<th>Week</th>
<th>Release Payment</th>
</tr>
</thead>
<tbody>
<tr ng-repeat="item in payout">
<td>{{item.value}}</td>
<td>
<input type="checkbox" ng-model="allCheckBox[$index]" ng-click="selectItem(item._id,selected,payout)">
</td>
</tr>
</tbody>
</table>
</div>
</div>

I have modified your code to make it working:
$scope.checkall=false;
$scope.allCheckBox=[];
$rootScope.selected = [];
$scope.payout = [{
'_id': 1,
value: 'Option1'
}, {
'_id': 2,
value: 'Option2'
}];
$scope.toggleAll = function() {
$scope.checkall = !$scope.checkall;
$rootScope.selected = [];
$scope.allCheckBox=[];
for (var i = 0; i < $scope.payout.length; i++) {
$scope.allCheckBox.push($scope.checkall);
if ($scope.checkall)
$rootScope.selected.push($scope.payout[i]);
}
}
$scope.selectItem = function(id) {
console.log('id', id);
var idx = $rootScope.selected.indexOf(id);
if (idx > -1) {
$rootScope.selected.splice(idx, 1);
} else {
$rootScope.selected.push(id);
}
if ($scope.payout.length == $rootScope.selected.length) {
$scope.checkall = true;
console.log($scope.checkall);
// $scope.checkall= $scope.checkall;
console.log('All checkboxes selected');
} else {
$scope.checkall = false;
console.log('Not All checkboxes selected');
}
}
html:
<div class="check_toggle" ng-click="toggleAll()">
select all
<input type="checkbox" aria-label="Art" ng-model="checkall" ng-click="toggleAll()"/>
</div>
<table>
<thead>
<tr>
<th>Week</th>
<th>Release Payment</th>
</tr>
</thead>
<tbody>
<tr ng-repeat="item in payout">
<td>{{item.value}}</td>
<td>
<div class="checkbox pay_check">
<input aria-label="Art" type="checkbox" ng-model="allCheckBox[$index]" ng-click="selectItem(item._id)">
</div>
</td>
</tr>
</tbody>
</table>
Plunk: https://plnkr.co/edit/SmabE9?p=preview

i did'nt read your question but to toggle all check boxes this code will be work.this is example you have to manipulate it.you can have a look here. https://plnkr.co/edit/qD7CABUF9GLoFCb8vDuO?p=preview
var app = angular.module("test", []);
app.controller('testctrl',function($scope){
$scope.options=[
{option:"option1",
selected:false ,
},
{option:"option1",
selected:false ,
},
{option:"option1",
selected:false ,
},
{option:"option1",
selected:false ,
},
{option:"option1",
selected:false ,
},
]
$scope.test=function(event){
if(event.currentTarget.checked==true)
{
var togglestatus=$scope.isAllSelected;
angular.forEach($scope.options,function(object){
object.selected=togglestatus
})
<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>
}else{
angular.forEach($scope.options,function(object){
object.selected=false
})
}
}
})

Related

Send data to controller via Javascript

I have a html table in with razor and I want to send some data from the table to a controller via Javascript.
I tried several different solutions but the data never seems to reach my controller while alerts are being hit. The breakpoints in the controller are never being hit which indicates to me that the data can't reach the controller.
I want the value of #item.PartId and the value of checked to be send to the controller.
<div class="Table">
{
<table id="table1" class="table table-striped TableData">
#{var id = 0;}
#foreach (var item in Model.PieceViewItems)
{
id++;
<tr id="#id">
<td>#id</td>
<td><label>#item.PartDescription</label> <br /> #item.PartId (#item.StatusCode)</td>
<td>#item.Supplier</td>
<td style="width: 100px !important">
#item.TijdOpO3 #if (item.TijdOpO3 == "1")
{<text>dag</text>}
else
{ <text>dagen</text>}
</td>
<td>#item.KeurCode</td>
<td>#item.PromiseDate</td>
<td>#item.WidthAndPartType</td>
<td>
#item.PieceLengthWithUnit <br /> #item.NrOfPieces #if (item.NrOfPieces == 1)
{<text>rol</text> }
else
{ <text>rollen</text>}
</td>
<td>
#if (item.NumberReceived == "0")
{<text>NIEUW</text> }
else
{ #item.NumberReceived}
</td>
<td>#item.VoorraadQty m</td>
<td style="width: 100px !important">
#item.SalesOrderQty m <br /> #item.NrOfSalesOrders #if (item.NrOfSalesOrders == 1)
{<text>order</text>}
else
{<text>orders</text>}
</td>
<td style="width: 100px !important">
#item.StalenOrdersQty m <br /> #item.NrOfStalenOrders #if (item.NrOfStalenOrders == 1)
{<text>order</text>}
else
{<text>orders</text>}
</td>
<td><input type="checkbox" name="IsChecked" onclick="ClickHandle(this)" style="width:30px;height:30px;margin-left:20px;margin-top:20px"> </td>
</tr>
}
</table>
</div>
Javascript
<script type="text/javascript">
$(function ClickHandle() {
$("input[name='IsChecked']").change(function (element) {
var table = document.getElementById("table1");
for (var i = 1; i < table.rows.length; i++) {
var row = table.rows[i];
var lastorder = row.cells[12].firstChild;
var check = lastorder.checked;
if (check) {
var x = document.getElementById("table1").getElementsByTagName("tr");
x[i].style.backgroundColor = "yellow";
}
else {
var x = document.getElementById("table1").getElementsByTagName("tr");
x[i].style.backgroundColor = null;
}
//post item.partid and value of check to controller here.
}
});
});
</script>
Controller
[HttpPost]
public ActionResult PostIsChecked(string partId, string isChecked)
{
Part part = new Part
{
id = partId,
isChecked = isChecked
};
//Do stuff
receipt.UpdateCheckedStatus(part);
}
You can try to put a hidden input into <tr></tr>,and set its value with #item.PartId.Then use ajax to post data to action.Here is a demo:
<div class="Table">
{
<table id="table1" class="table table-striped TableData">
#{var id = 0;}
#foreach (var item in Model.PieceViewItems)
{
id++;
<tr id="#id">
<td>#id</td>
<td><label>#item.PartDescription</label> <br /><input hidden value=#item.PartId/> #item.PartId (#item.StatusCode)</td>
<td>#item.Supplier</td>
<td style="width: 100px !important">
#item.TijdOpO3 #if (item.TijdOpO3 == "1")
{<text>dag</text>}
else
{ <text>dagen</text>}
</td>
<td>#item.KeurCode</td>
<td>#item.PromiseDate</td>
<td>#item.WidthAndPartType</td>
<td>
#item.PieceLengthWithUnit <br /> #item.NrOfPieces #if (item.NrOfPieces == 1)
{<text>rol</text> }
else
{ <text>rollen</text>}
</td>
<td>
#if (item.NumberReceived == "0")
{<text>NIEUW</text> }
else
{ #item.NumberReceived}
</td>
<td>#item.VoorraadQty m</td>
<td style="width: 100px !important">
#item.SalesOrderQty m <br /> #item.NrOfSalesOrders #if (item.NrOfSalesOrders == 1)
{<text>order</text>}
else
{<text>orders</text>}
</td>
<td style="width: 100px !important">
#item.StalenOrdersQty m <br /> #item.NrOfStalenOrders #if (item.NrOfStalenOrders == 1)
{<text>order</text>}
else
{<text>orders</text>}
</td>
<td><input type="checkbox" name="IsChecked" onclick="ClickHandle(this)" style="width:30px;height:30px;margin-left:20px;margin-top:20px"> </td>
</tr>
}
</table>
</div>
js:
$("input[name='IsChecked']").change(function () {
var checked = this.checked;
var PartId = $(this).parent().parent().find("input")[0].value;
$.ajax({
type: "POST",
url: "PostIsChecked",
data: { "isChecked": checked, "partId": PartId},
success: function (data) {
}
});
});

How can I select all checkboxes in mvc

This code below select only one by one checkbox, how can I transform this code so I can select all checkboxes by one click, but I need my variables to stay defined.
$('.checktip').click(function () {
var iduser = $('.iduser').val();
var idtip = $(this).attr('idtip');
var che = $(this).prop('checked');
$.ajax({
url: UrlSettingsDocument.OrgUnits,
data: { iduser: iduser, idtip: idtip, che: che },
type: "POST",
success: function (result) {
if (result.result == "Redirect") {
window.location = result.url;
}
}
});
});
I using this variables for controller where I save this values in database when I check them or unchecked.
Here is my html code
<input type="hidden" value="#ViewBag.iduser" id="iduser" />
<hr />
<table class="table table-striped grid-table">
<tr>
<th>Samp</th>
<th>Id of Book</th>
<th>
//Checkbox for check all *(NOT IMPLEMENTED)*
<input type="checkbox" id="box" name="checkAll" />
</th>
</tr>
#foreach (var item in (IEnumerable<cit.Models.getCheIdTip_Result>)Model)
{
<tr>
<td>#item.idtip</td>
<td>#item.tipname</td>
<td>
#*#Html.CheckBox(item.id.ToString(), item.iduser == ViewBag.iduser ? true : false, new { idtip = item.idtip, #class = "checktip" })*#
<div class="pure-checkbox">
<input type="checkbox" idtip="#item.idtip" class="checktip" checked="#(item.iduser == ViewBag.iduser ? true : false)" name="#item.id.ToString()" id="#item.id.ToString()" />
<label for="#item.id.ToString()"></label>
</div>
</td>
</tr>
}
</table>
Following code should work with your code
$('#box').click(function(){ $('.checktip').prop('checked', true); }};

How to check if tr is show/hide based on dropdown selection

I have selection tag with three options:important,middle important, not so important; and on each selection I want to show only those elements from my table which contains this data.
On the other hand I want to add logic which will tell me that certain tr is show or hide ( I want to add showed materials to array)
Here is my code , how should I implement this logic?
<select id="mySelector" class="styled-select slate" style="width:280px; height:35px">
<option value='important'>აირჩიე</option>
<option value='very important'>very important</option>
<option value='middle important'>middle important</option>
<option value='not so important'>not so important</option>
</select>
//selection code
$(document).ready(function($) {
$('#mySelector').change( function(){
var selection = $(this).val();
$('table')[selection? 'show' : 'hide']();
if (selection) {
$.each($('#myTable tbody tr'), function(index, item) {
$(item)[$(item).is(':contains('+ selection +')')? 'show' : 'hide']();
});
}
});
});
$scope.selectAll = function(){
document.querySelector('#myTable1').style.display = 'block';
for (var i = 0; i < $scope.realJsonArray.length; i++) {
var item = $scope.realJsonArray[i];
console.log(item.id+"id======================");
issync1(item);}
};
<tr id="input1">
<td><input type="checkbox" ng-change="sync(selected[item.id],item)" ng-checked="isChecked(item.id)" name="checkData" ng-model="selected[item.id]" ng-false-value="undefined" /></td>
<td>{{item.id}}</td>
<td>{{item.organizationNameEN}}</td>
<td>{{item.organizationNameGE}}</td>
<td>{{item.priority}}</td>
<td><button class="btn btn-default btn-xs" ng-click="toggle($index)"><span class="glyphicon glyphicon-eye-open"></span></button></td>
</tr>
p.s my table tag id is myTable1
You can use $.toggleClass():
$(function() {
$('input').on('change', function(e) {
$('p').toggleClass('hide', this.checked);
});
});
.hide {
display: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<label><input type='checkbox'/>Show/Hide</label>
<p>This is para</p>
function which will tell me if row is selected ( if it is selected it
can return true and false in other way for example)
Yes, you can lookup using input checkbox which you have for each row.
Option 1: finding using checkboxes itself
$(function() {
$('button').on('click', function() {
var rows = $('input[name=checkData]:checked').parents('tr');
console.log('checked rows', 0 !== rows.length);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
<tr id='input1'>
<td>
<input name="checkData" type='checkbox' />
</td>
</tr>
<tr id='input2'>
<td>
<input name="checkData" type='checkbox' checked='' />
</td>
</tr>
<tr id='input3'>
<td>
<input name="checkData" type='checkbox' />
</td>
</tr>
</table><button>Check</button>
Refer following code may this would meet you requirement !!
<table>
<tr><td></td><td>id</td> <td>name</td> <td>address</td> <td>classA</td> <td>classB</td></tr>
<tr ng-repeat="employee in employees">
<td><input type="checkbox" ng-model="employee.checked" ng-true-value="1" ng-false-value="0"></td>
<td>{{employee.id}}</td>
<td>{{employee.name}}</td>
<td>{{employee.address}}</td>
<td><input type="checkbox" ng-model="employee.classA"></td>
<td><input type="checkbox" ng-model="employee.classB"></td>
</tr>
</table>
app.controller('MainCtrl', function($scope) {
$scope.employees = [
{ id:"1", name: "A", address: "A1", classA: true, classB: true },
{ id:"2", name: "B", address: "A2", classA: false, classB: true },
{ id:"3", name: "C", address: "A3", classA: true, classB: false },
{ id:"4", name: "D", address: "A4", classA: false, classB: true },
{ id:"5", name: "E", address: "A5", classA: false, classB: true },
];
$scope.getSelected = function () {
var ar = $scope.employees.filter(
function (value) {
if (value.checked == 1) {
return true;
} else {
return false;
}
}
);
return ar;
};
});

ng-repeat and ng-scrollbar doesn't work together

I'm just starting Angular JS and trying to have a scrollbar appearing as I add an element in the list which would be populated in the box of the contents.
I installed ng-scrollbar from here. https://github.com/asafdav/ng-scrollbar
HTML:
<link rel="stylesheet" href="../dist/ng-scrollbar.min.css" >
<style>
.scrollme {
max-height: 100px;
}
</style>
</head>
<body>
<div ng-app="DemoApp">
<div class="container" ng-controller="DemoController">
<table border="0" width="100%">
<div class="scrollme" ng-scrollbar rebuild-on="rebuild:me" is-bar-shown="barShown">
<tr>
<th width="2%"></th>
<th width="14%">Name</th>
<th width="85%">Address</th>
</tr>
<tr>
<td>
<img src="addImageButton.png" ng-click="addRow()" />
</td>
<td class="inlineBlock">
<input type="text" ng-model="row.name" />
</td>
<td>
<input ng-model="row.addr" />
</td>
</tr>
<tr ng-repeat="row in rowList">
<td>
<img src="removeImageButton.png"ng-click="removeRow($index)" />
</td>
<td>{{row.name}}</td>
<td>{{row.client}}</td>
</tr>
</div>
</table>
</div>
</div>
</body>
JavaScript:
(function () {
'use strict';
var app = angular.module('DemoApp', ['ngScrollbar']);
app.controller('DemoController', DemoController);
function DemoController($scope) {
// portfolio and broker tabs
$scope.row = {}
$scope.row.name = "";
$scope.row.addr = "";
$scope.rowList = [];
// adding a row to list
$scope.addRow = function() {
var data = {};
data.name = $scope.row.name;
data.addr = $scope.row.addr;
$scope.rowList.push(data);
$scope.row.name = "";
$scope.row.addr = "";
console.log($scope.rowList);
}
// removing a row from the list
$scope.removeRow = function(obj) {
console.log('end' + $scope.rowList);
if(obj != -1) {
$scope.rowList.splice(obj, 1);
}
}
$scope.$on('scrollbar.show', function(){
console.log('Scrollbar show');
});
$scope.$on('scrollbar.hide', function(){
console.log('Scrollbar hide');
});
// $scope.$on('loopLoded', function(evt, index) {
// if(index == $scope.me.length-1) {
// $scope.$broadcast('rebuild:me');
// }
// });
}
})();
It's part of my code so it might not fully make sense. But the way it works is that if I pressed the addImageButton, it would add a row which will add a row on the web. And conversely, removeImageButton will delete a row which will show on the web immediately. I need a scroll bar appearing once it reaches the height 100px. I checked the last answer of the ng-scrollbar is not working with ng-repeat
as well but it didn't work. Would be great if I could get some help with the detailed explanation. :) Thanks!
Figured out! I need to put the broadcast method in addRow and removeRow methods. Also, I had to put the out from the

jQuery code to get data of other columns when the row is checked

This is my html code and I would like to get the data of rows in which checkbox is checked.
HTML
<!DOCTYPE html>
<html>
<body>
<div >
<header>
<h1>
<span>Expand Fed</span>
</h1>
</header>
<h1>
<span>Fed Members </span>
</h1>
<table id="my-table">
<thead>
<tr>
<td>Service Set</td>
<td>Available Devices</td>
<td>Status</td>
<td>Add</td>
</tr>
</thead>
</table>
<footer>
<div>
<input id="so-fedExpand-expand-button" class="button primary" type="submit" value="Expand"/>
Cancel
</div>
</footer>
</div>
</body>
</html>
jQuery
var FedExpandView = (function() {
var EXPAND = '#so-fedExpand-expand-button';
function FedExpandView() {
this.init = function () {
$(EXPAND).on('click', onExpand);
var data = [{ SSet: "Service Set 1", ADevices: '46', Status: "Online"},
{ SSet: "Service Set 2", ADevices: '47', Status: "Online"},
{ SSet: "Service Set 3", ADevices: '48', Status: "Online"}];
$('#my-table').dataTable({
bPaginate : false,
bFilter : false,
bInfo : false,
aaData: data,
aoColumns : [
{mDataProp: 'SSet', id: 'so-fed-ss'},
{mDataProp: 'ADevices', id: 'so-fed-adev'},
{mDataProp: 'Status', id: 'so-fed-status'},
{sDefaultContent: '',
fnRender: function (oObj) {
return '<input type="checkbox" id="so-fed-checkbox" name="select"">';
},
sWidth: '10px', sClass: "icon"}
]
}).rowReordering().
addClass('reorderable');
$('#my-table tbody tr').first().addClass('selected');
this.resume();
}
this.resume = function () {
}
}
return new FedExpandView();
}());
This is how i am getting static data into the table...
can some one help me in getting data of the remaining rows...
Try this example
JS
function checkTable() {
var rowElem;
$('#my-table tr').each(function(idx, elem) {
rowElem = $(elem);
if(rowElem.find('input').is(':checked')) {
console.log('row ' + (idx + 1) + ' is checked');
console.log('data1 is: ' + rowElem.find('.data1').html());
console.log('data2 is: ' + rowElem.find('.data2').html());
}
});
}
HTML
<table id="my-table">
<tr>
<td>
<input type="checkbox">
</td>
<td class="data1">Row1 Data1</td>
<td class="data2">Row1 Data2</td>
</tr>
<tr>
<td>
<input type="checkbox">
</td>
<td class="data1">Row2 Data1</td>
<td class="data2">Row2 Data2</td>
</tr>
<tr>
<td>
<input type="checkbox">
</td>
<td class="data1">Row3 Data1</td>
<td class="data2">Row3 Data2</td>
</tr>
</table>
<button onclick="checkTable()">Check table</button>
Plunker demo
$("#my-table tbody tr").on('click', function (event) {
serviceSets.length = 0;
var rows = $('table tr td :checkbox:checked').map(function () {
return $(this).val();
}).get();
$( rows ).each(function() {
var that = this;
$( Tabledata ).each(function() {
if(that == this.ssid)
{
serviceSets.push(this);
}
});
});
});

Categories