Angular - How to make results show, only if unchecked - javascript

I have code that filters and shows the result of the box checked. When all the checkboxes are unchecked it shows all the results and when boxes are checked it only shows the boxes selected.
However, I'm trying to show all the results when the boxes are unchecked and if a check box is checked then it doesn't show that specific result, while continuing to show the boxes that are unchecked.
controller.js
function AdvisorListCtrl( $location, $scope, db) {
$scope.orderProp = 'number';
$scope.courseCheckboxes = {};
$scope.teacherCheckboxes = {};
$scope.courses = db.courses.query({order:$scope.orderProp, name:$scope.query});
function getChecked(obj){
var checked = [];
for(var key in obj)
if(obj[key]) checked.push(key);
return checked;
}
$scope.searchFilter = function(row){
var courChecked = getChecked($scope.courseCheckboxes);
var teachChecked = getChecked($scope.teacherCheckboxes);
if (courChecked.length == 0 && teachChecked.length == 0)
return true;
else {
if ($scope.courseCheckboxes[row.name])
return true;
else {
return row.teacher.split(/,\s*/).some(function(teach){
return $scope.teacherCheckboxes[teach];
});
}
}
}
}
html
<li><b><h2>Filter by Class</h2></b></li>
<li ng-repeat="course in courses | orderBy:['-status', 'name']">
<label>
<input type="checkbox" ng-model="courseCheckboxes[course.name]" />{{course.name}}
</label>
</li>

I had misunderstood your question so I re-edited the answer.
When searchFilter(record) returns false the record is filtered out (and not displayed).
Here is a version of the filter that should do the opposite of what was doing (hide the checked merchants, and the merchants containing the checked brands). Hope this helps.
html
<div ng-repeat="record in records | filter: searchFilter">
{{record.Description}}
js
$scope.searchFilter = function(row){
var mercChecked = getChecked($scope.merchantCheckboxes);
var brandChecked = getChecked($scope.brandCheckboxes);
if(mercChecked.length == 0 && brandChecked.length == 0)
return true;
else{
if($scope.merchantCheckboxes[row.MerchantName]){
return false; // <----------------- changed here true to false
} else {
// changed here adding !
return !row.BrandList.split(/,\s*/).some(function(brand){
return $scope.brandCheckboxes[brand];
});
}
}
};

Related

checking whether or not any checkbox input is checked from array of input

I have a node list of chechbox inputs
const searchSizeSelectionInputs = document.querySelectorAll(
".sizeHolderFilter > input")
I have written a function to check whether or not any checkbox is checked or not, the function is
const activationChecker = ()=>{
if (
availabilityInStoreOptions[0].classList.contains("activeSortOptionSP") ||
availabilityInStoreOptions[1].classList.contains("activeSortOptionSP")
) {
isAvailabilityInStorActive = true;
}
if( !availabilityInStoreOptions[0].classList.contains("activeSortOptionSP") &&
!availabilityInStoreOptions[1].classList.contains("activeSortOptionSP")) {
isAvailabilityInStorActive = false;
}
searchSizeSelectionInputs.forEach(input => {
if (input.checked) {
isSizeInputChecked = true;
} else {
let isSizeInputChecked = false;
}
});
searchColorSelectionInputs.forEach(input => {
if (input.checked) {
isColorInputChecked = true;
} else {
let isColorInputChecked = false;
}
});
};
the thing is, when I check the result of isSizeInputChecked or isColorInputChecked it gives me faulty answers, for example when I check the checkbox it gives me true and when I uncheck the checkbox it still gives me true, I tested the same code on one single object and it works beautifully,I believe I do have a problem on doing this on a node list. This must be the wrong way:
searchSizeSelectionInputs.forEach(input => {
if (input.checked) {
isSizeInputChecked = true;
} else {
let isSizeInputChecked = false;
}
How can I check if any checkbox is checked or not any of them is checked?
function getCheckedData() {
let atleastOneChecked=Array.from(document.querySelectorAll('.checkbox'))
.some(
function(inputCheckbox) {
return inputCheckbox.checked;
}
);
let allChecked=Array.from(document.querySelectorAll('.checkbox'))
.every(
function(inputCheckbox) {
return inputCheckbox.checked;
}
);
console.log('atleastOneChecked',atleastOneChecked);
console.log('allChekecked',allChecked);
}
<input type="checkbox" class='checkbox'>
<input type="checkbox" class='checkbox'>
<button onclick="getCheckedData()">Get checked data</button>
The document.querySelectorAll returns a NodeList and it is not an array. We have to convert node list into an array using Array.from and use the some function from Array to get atleast one of the element is checked or not.

Validating different types of form inputs with criterias

I want to get the answers to a form upon submission and parse them to JSON.
This works quite good but I want some validation before sending the data.
I tried a lot of variations of the snippet down below but am still stuck.
Steps:
Prevent default event on "send"
Get Form
Iterate through the elements of the form
Eliminate empty items and their value
If checkbox is checked: value = true
Store correct items in data
Return data
Somehow I can't get to work steps 4 and 5 work at the same time, every time I get one of them to work I screw over the other one.
In this snippet, the checkbox works as intented but the textfield doesn't:
If anybody can point me in the right direction with the if/else statements or something like that it would be greatly appreciated.
document.addEventListener('DOMContentLoaded', function(){
var data = {};
var formToJSON = function formToJSON(form) {
var data = {};
for (var i = 0; i < form.length; i++) {
var item = form[i];
//looking for checkbox
if (item.value =="") {
continue;
}
else {
if (item.checked == false) {
data[item.name] = false;
}
else {
data[item.name] = item.value;
}
}
}
return data; };
var dataContainer = document.getElementsByClassName('results__display')[0];
form = document.getElementById('formular').querySelectorAll('input,select,textarea');
butt = document.getElementById('knopfabsenden');
butt.addEventListener('click', function (event) {
event.preventDefault();
handleFormSubmit(form = form);
});
var handleFormSubmit = function handleFormSubmit(event) {
var data = formToJSON(form);
dataContainer.textContent = JSON.stringify(data, null, " ");
}
}, false);
<div id="formular">
<label class="formular__label" for="machineName">Textfield Test</label>
<input class="formular__input formular__input--text" id="machineNumber" name="machineNumber" type="text"/>
<br>
<input class="formular__input formular__input--checkbox" id="checkTest" name="checkTest" type="checkbox" value="true"/>
<label class="formular__label formular__label--checkbox" for="checkTest">Checkbox Test</label>
<br>
<button class="formular__button" id="knopfabsenden" type="submit">Submit</button>
</div>
<div class="results">
<h2 class="results__heading">Form Data</h2>
<pre class="results__display-wrapper"><code class="results__display"></code></pre>
</div>
The problem is .checked will always be false if it doesn't exist. So the text field gets the value false.
for (var i = 0; i < form.length; i++) {
var item = form[i];
//looking for checkbox
if (item.value ==="") {
continue;
}
else {
if (item.type === "text") {
data[item.name] = item.value;
}
else if (item.type === "checkbox"){
data[item.name] = item.checked;
}
}
}
In this code snippet I check the type of the input and handle it accordingly. also notice I use the === operator and not the == operator as a best practice (Difference between == and === in JavaScript)

Validate checkbox with AngularJs

Again i'm having trouble with checkboxes. I'm getting info from an API and showing like checkbox. The problem comes when i'm triying to add a validation. This is a part of my code:
(function() {
'use strict';
var fact = {
templateUrl: './app/components/fact.components.html',
controller: factCtrl
};
angular.module('fApp').component('odcFacturas', fact);
factCtrl.$inject = ["$scope", "couponApi"];
function factCtrl($scope, couponApi) {
var vm = this;
vm.clientOrder = null;
vm.all = false;
vm.sendData = function() {
vm.apiData = couponApi.get({
idOrder: vm.idOrder
}).$promise.then(function(data) {
for (var i = 0; i < data.Response.length; i++) {
data.Response[i].Select = vm.all;
}
vm.coupons = data.Response;
vm.combo = data.Response.length > 0;
});
}
Here i call the info, and the next part of my code check all the checkboxes:
vm.selectAll = function() {
for (var i = 0; i < vm.coupons.length; i++) {
vm.coupons[i].Select = vm.all;
}
if (vm.all == 0) {
alert("Select at least one coupon");
}
}
How can I trigger three validations with a submit button? I mean: what I want to do is validate three cases:
if the checkbox "select all checkboxes" is checked, submit
if there's no selected checkboxes, show the alert message
if there's at least one checkbox (or 'n' checkboxes) selected,
submit
On the HTML view i have this:
<div class ="container-fluid">
<div class="row">
<div class="col-md-6">
<div class="cbx input-group">
<div class="checkbox" name="imtesting" ng-show="$ctrl.coupons.length > 0">
<label><input type="checkbox"
ng-show="$ctrl.coupons.length > 0"
name="allCoupons"
ng-model="$ctrl.all"
ng-click="$ctrl.selectAll()"/>Select all coupons</label>
<ul>
<li ng-repeat="c in $ctrl.coupons">
<input type="checkbox"
name="couponBox"
ng-model="c.Select"
ng-click="$ctrl.result()"
required/>{{c.CodeCoupon}}
<br>
</li>
</ul>
<label class="label label-danger" ng-show="submitted == true && !ctrl.newTest()">Select at least one coupon</label>
</div>
</div>
</div>
</div>
Hope you can help me.
Thanx in advance.
You can use the Select property from each coupon object like
vm.canSubmit = function() {
for(var i = 0; i< vm.coupons.length; i++)
{
if (vm.coupons[i].Select) {
return true;
}
}
return false;
}
Redo the way you are handling your selectsAll function. When you are using angular there is a thing called scope.$apply that is actually running which tells the dom to update if the object or properties have changed. Sometimes if you use for loops the way you are using them it wont register a change.
Try this and it should work:
vm.selectAll = function()
{
vm.all = !vm.all;
vm.coupons.forEach(function(o){
o.Select = vm.all;
})
}
vm.submit = function(){
var checked = 0;
vm.coupons.forEach(function(o){
if(o.Select === true)
checked +=1;
})
if(vm.all || checked > 0){
//submit here
}
else if(checked === 0){
//error
}
}
This will work both ways. If checked it will check all and if unchecked it will uncheck all. That validation will work for all three scenarios.

Validating a checkbox after already validating other sections of a form [duplicate]

I have a form with multiple checkboxes and I want to use JavaScript to make sure at least one is checked. This is what I have right now but no matter what is chosen an alert pops up.
JS (wrong)
function valthis(){
if (document.FC.c1.checked) {
alert ("thank you for checking a checkbox")
} else {
alert ("please check a checkbox")
}
}
HTML
<p>Please select at least one Checkbox</p>
<br>
<br>
<form name = "FC">
<input type = "checkbox" name = "c1" value = "c1"/> C1
<br>
<input type = "checkbox" name = "c1" value = "c2"/> C2
<br>
<input type = "checkbox" name = "c1" value = "c3"/> C3
<br>
<input type = "checkbox" name = "c1" value = "c4"/> C4
<br>
</form>
<br>
<br>
<input type = "button" value = "Edit and Report" onClick = "valthisform();">
So what I ended up doing in JS was this:
function valthisform(){
var chkd = document.FC.c1.checked || document.FC.c2.checked||document.FC.c3.checked|| document.FC.c4.checked
if (chkd == true){
} else {
alert ("please check a checkbox")
}
}
I decided to drop the "Thank you" part to fit in with the rest of the assignment. Thank you so much, every ones advice really helped out.
You should avoid having two checkboxes with the same name if you plan to reference them like document.FC.c1. If you have multiple checkboxes named c1 how will the browser know which you are referring to?
Here's a non-jQuery solution to check if any checkboxes on the page are checked.
var checkboxes = document.querySelectorAll('input[type="checkbox"]');
var checkedOne = Array.prototype.slice.call(checkboxes).some(x => x.checked);
You need the Array.prototype.slice.call part to convert the NodeList returned by document.querySelectorAll into an array that you can call some on.
This should work:
function valthisform()
{
var checkboxs=document.getElementsByName("c1");
var okay=false;
for(var i=0,l=checkboxs.length;i<l;i++)
{
if(checkboxs[i].checked)
{
okay=true;
break;
}
}
if(okay)alert("Thank you for checking a checkbox");
else alert("Please check a checkbox");
}
If you have a question about the code, just comment.
I use l=checkboxs.length to improve the performance. See http://www.erichynds.com/javascript/javascript-loop-performance-caching-the-length-property-of-an-array/
I would opt for a more functional approach. Since ES6 we have been given such nice tools to solve our problems, so why not use them.
Let's begin with giving the checkboxes a class so we can round them up very nicely.
I prefer to use a class instead of input[type="checkbox"] because now the solution is more generic and can be used also when you have more groups of checkboxes in your document.
HTML
<input type="checkbox" class="checkbox" value=ck1 /> ck1<br />
<input type="checkbox" class="checkbox" value=ck2 /> ck2<br />
JavaScript
function atLeastOneCheckboxIsChecked(){
const checkboxes = Array.from(document.querySelectorAll(".checkbox"));
return checkboxes.reduce((acc, curr) => acc || curr.checked, false);
}
When called, the function will return false if no checkbox has been checked and true if one or both is.
It works as follows, the reducer function has two arguments, the accumulator (acc) and the current value (curr). For every iteration over the array, the reducer will return true if either the accumulator or the current value is true.
the return value of the previous iteration is the accumulator of the current iteration, therefore, if it ever is true, it will stay true until the end.
Check this.
You can't access form inputs via their name. Use document.getElements methods instead.
Vanilla JS:
var checkboxes = document.getElementsByClassName('activityCheckbox'); // puts all your checkboxes in a variable
function activitiesReset() {
var checkboxesChecked = function () { // if a checkbox is checked, function ends and returns true. If all checkboxes have been iterated through (which means they are all unchecked), returns false.
for (var i = 0; i < checkboxes.length; i++) {
if (checkboxes[i].checked) {
return true;
}
}
return false;
}
error[2].style.display = 'none'; // an array item specific to my project - it's a red label which says 'Please check a checkbox!'. Here its display is set to none, so the initial non-error label is visible instead.
if (submitCounter > 0 && checkboxesChecked() === false) { // if a form submit has been attempted, and if all checkboxes are unchecked
error[2].style.display = 'block'; // red error label is now visible.
}
}
for (var i=0; i<checkboxes.length; i++) { // whenever a checkbox is checked or unchecked, activitiesReset runs.
checkboxes[i].addEventListener('change', activitiesReset);
}
Explanation:
Once a form submit has been attempted, this will update your checkbox section's label to notify the user to check a checkbox if he/she hasn't yet. If no checkboxes are checked, a hidden 'error' label is revealed prompting the user to 'Please check a checkbox!'. If the user checks at least one checkbox, the red label is instantaneously hidden again, revealing the original label. If the user again un-checks all checkboxes, the red label returns in real-time. This is made possible by JavaScript's onchange event (written as .addEventListener('change', function(){});
You can check that atleast one checkbox is checked or not using this simple code. You can also drop your message.
Reference Link
<label class="control-label col-sm-4">Check Box 2</label>
<input type="checkbox" name="checkbox2" id="checkbox2" value=ck1 /> ck1<br />
<input type="checkbox" name="checkbox2" id="checkbox2" value=ck2 /> ck2<br />
<script>
function checkFormData() {
if (!$('input[name=checkbox2]:checked').length > 0) {
document.getElementById("errMessage").innerHTML = "Check Box 2 can not be null";
return false;
}
alert("Success");
return true;
}
</script>
< script type = "text/javascript" src = "js/jquery-1.6.4.min.js" > < / script >
< script type = "text/javascript" >
function checkSelectedAtleastOne(clsName) {
if (selectedValue == "select")
return false;
var i = 0;
$("." + clsName).each(function () {
if ($(this).is(':checked')) {
i = 1;
}
});
if (i == 0) {
alert("Please select atleast one users");
return false;
} else if (i == 1) {
return true;
}
return true;
}
$(document).ready(function () {
$('#chkSearchAll').click(function () {
var checked = $(this).is(':checked');
$('.clsChkSearch').each(function () {
var checkBox = $(this);
if (checked) {
checkBox.prop('checked', true);
} else {
checkBox.prop('checked', false);
}
});
});
//for select and deselect 'select all' check box when clicking individual check boxes
$(".clsChkSearch").click(function () {
var i = 0;
$(".clsChkSearch").each(function () {
if ($(this).is(':checked')) {}
else {
i = 1; //unchecked
}
});
if (i == 0) {
$("#chkSearchAll").attr("checked", true)
} else if (i == 1) {
$("#chkSearchAll").attr("checked", false)
}
});
});
< / script >
Prevent user from deselecting last checked checkbox.
jQuery (original answer).
$('input[type="checkbox"][name="chkBx"]').on('change',function(){
var getArrVal = $('input[type="checkbox"][name="chkBx"]:checked').map(function(){
return this.value;
}).toArray();
if(getArrVal.length){
//execute the code
$('#msg').html(getArrVal.toString());
} else {
$(this).prop("checked",true);
$('#msg').html("At least one value must be checked!");
return false;
}
});
UPDATED ANSWER 2019-05-31
Plain JS
let i,
el = document.querySelectorAll('input[type="checkbox"][name="chkBx"]'),
msg = document.getElementById('msg'),
onChange = function(ev){
ev.preventDefault();
let _this = this,
arrVal = Array.prototype.slice.call(
document.querySelectorAll('input[type="checkbox"][name="chkBx"]:checked'))
.map(function(cur){return cur.value});
if(arrVal.length){
msg.innerHTML = JSON.stringify(arrVal);
} else {
_this.checked=true;
msg.innerHTML = "At least one value must be checked!";
}
};
for(i=el.length;i--;){el[i].addEventListener('change',onChange,false);}
<label><input type="checkbox" name="chkBx" value="value1" checked> Value1</label>
<label><input type="checkbox" name="chkBx" value="value2"> Value2</label>
<label><input type="checkbox" name="chkBx" value="value3"> Value3</label>
<div id="msg"></div>
$('input:checkbox[type=checkbox]').on('change',function(){
if($('input:checkbox[type=checkbox]').is(":checked") == true){
$('.removedisable').removeClass('disabled');
}else{
$('.removedisable').addClass('disabled');
});
if(($("#checkboxid1").is(":checked")) || ($("#checkboxid2").is(":checked"))
|| ($("#checkboxid3").is(":checked"))) {
//Your Code here
}
You can use this code to verify that checkbox is checked at least one.
Thanks!!

Checkbox state with javascript

I have list of checkboxes in my jsp page.Based on Main checkbox i have to check/uncheck all child check boxes.
1)Take i have 10 child checkboxes and have main checkbox.When i check Main checkbox,i able to select all child checkboxes.if user unselect any child checkbox,i able to unselect
main checkbox.so here out of 10 childcheckboxes,i unselect 1 checkbox ,based on this i unchecked main checkbox.
But here my Question,if user checks that checkbox again,so here my status is selected all 10 checkboxes.So i should even checks the main checkbox too.
Add onclick handlers to the checkboxes.
Keep a count.
If it is checked add 1, if it becomes unchecked subtract one.
If the total equals the number of checkboxes, check the check all checkbox.
Here's a rough guide to how to do it:
<script type="text/javascript">
var checkboxCheck = (function() {
var boxes;
var mainCb;
// If all checkboxes checked, return true
function allChecked() {
var i = boxes.length;
while (i--) {
if (!boxes[i].checked) return false;
}
return true;
}
// If value is in array, return true
function oneOf(value, array) {
var i = array.length;
while(i--) {
if (array[i] == value) return true;
}
return false;
}
// Main function
return function(evt, el) {
// Get the element that was clicked on
var target = evt.target || evt.srcElement;
// Initialise boxes if not done already
if (!boxes) {
boxes = [];
var o = el.getElementsByTagName('input');
for (var i=o.length; --i;) {
if (o[i].type == 'checkbox') {
boxes.push(o[i]);
}
}
}
// Initialise mainCb if not done already
if (!mainCb) {
mainCb = document.getElementById('mainCb');
}
// If the click was on one of the checkboxes
if (oneOf(target, boxes)) {
// If they're all checked, check mainCb
// otherwise uncheck mainCb
mainCb.checked = allChecked(boxes);
// If the click was on mainCb
} else if (target == mainCb) {
// Set all checkboxes to same state as mainCb
for (var j=boxes.length; j--;) {
boxes[j].checked = mainCb.checked;
}
}
}
}())
</script>
<fieldset onclick="checkboxCheck(event, this)">
<label for="main">Check all<input type="checkbox" id="mainCb" value="0"></label>
<br>
<label for="cb0">0<input type="checkbox" id="cb0" value="0"></label>
<br>
<label for="cb1">1<input type="checkbox" id="cb1" value="1"></label>
<br>
<label for="cb2">2<input type="checkbox" id="cb2" value="2"></label>
</fieldset>

Categories

Resources