Validate checkbox with AngularJs - javascript

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.

Related

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)

Disable CheckBox Dynamically using JQuery

I have a collection of checkboxes within a form. I am looping through the collection to check and/or disable the checkboxes. The checking works fine; however, I am having an issue with checking if the checkbox is disabled or not. It always return false even when the checkbox is enabled. I looked at the code over and over, and I could not see a anything that could cause this to happen.
Partial HTML File
<label class="col-lg-3"><div style="padding-left:5px;">View Department</div></label>
<div class="col-lg-1"><input id="Accounting" name="Accounting" type="checkbox" /> </div>
<label class="col-lg-3"> Finance</label>
<div class="col-lg-1"><input id="Finance" name="Finance" type="checkbox" /></div>
<label class="col-lg-3"> Marketing</label>
<div class="col-lg-1"><input id="Marketing" name="Marketing" type="checkbox" /></div>
<div class="col-lg-12">
<hr style="width:100%;" />
</div>
//This is how I disable the checkbox
var collection = document.getElementById('DepartmentClassModal').getElementsByTagName('input');
if (typeof (e) !== 'undefined') {
if (e) {
switch (e) {
case 'Education':
for (var i = 0; i < collection.length ; i++) {
if ((collection[i].id == 'Accounting') || (collection[i].id == 'Finance')) {
collection[i].disabled = true
} else {
collection[i].disabled = false
}
}
break;
}
}
}
//The rendering HTML
<input checked="checked" id="Accounting" name="Accounting" type="checkbox" disabled>
//checking if the field is disabled or not
var isAccountingDisabled = $('#Accounting').is(':disabled');
//The above code always return false. Why is that?
I added a screen shot of the checkbox property showing that the checkbox is automatically checked and disabled. Even though the checkbox is rendering as disabled, the property does not show it as being disabled.
You can't have multiple elements with the same id. In your looping structure you can add the index of the loop also to the id, so that it will be unique. (Accounting1, Accounting2...)
Change your code to something like this
var checkBoxesCollection = $("#yourparentelement").find("input:checkbox[name='Accounting']");
$.each(checkBoxesCollection, function(){
if (this.disabled) {
};
});
http://jsfiddle.net/eanamztz/
Use === instead of ==
for (var i = 0; i < collection.length ; i++) {
if ((collection[i].id === 'Accounting') || (collection[i].id === 'Finance')) {
collection[i].disabled = true
} else {
collection[i].disabled = false
}
}
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Comparison_Operators
I was not able to read the property using $('#Accounting').is(':checked'); however, I was able to read them using the syntax below.
var collection = document.getElementById('DepartmentClassModal').getElementsByTagName('input');
$.each(collection, function (index, item) {
ListDepartments[item.name + "Disabled"] = item.disabled;
})

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!!

JQuery Validated Form Not Submitting

I have a form that I am using on my site and it is validated with some simple JQuery validation. Problem is it's not submitting or doing anything really when I change the values. Here is my code:
<form id="radForm" method="post" action="events.php?type=rad">
<div class="searchBoxLeft searchBoxRad"></div>
<div class="searchBoxMiddle">
<input id="radSearch" type="text" class="searchBoxInput searchBoxShort" value="<?php echo $yourradius; ?>" />
<label class="searchBoxLabel">Mile Radius of Your Address</label>
</div>
<div id="radButton" class="searchBoxRight"></div>
<div class="clearLeft"></div>
</form>
<script>
$(document).ready(function()
{
var radsearchok = 0;
//Rad search
$('#radSearch').blur(function()
{
var radsearch=$("#radSearch").val();
if(radsearch < 2){
$('#radSearch').addClass("searchError");
radsearchok = 0;
}
else if(radsearch > 50){
$('#radSearch').addClass("searchError");
radsearchok = 0;
}
else{
$('#radSearch').addClass("searchSuccess");
radsearchok = 1;
}
});
// Submit button action
$('#radButton').click(function()
{
if(radsearchok == 1)
{
$("#radForm").submit();
}
else
{
$('#radSearch').addClass("searchError");
}
return false;
});
//End
});
</script>
Can anyone see what is wrong with this?
You need to go back and set the .val() property again of your form, otherwise it will take the original value of .val() not radsearch;
Not sure if you actually want to update .val() though or just attach a property. Some options:
Right before the closing brace of .blur --> }); add"
$("#radSearch").val(radsearch);
Or:
Add a hidden input to your form with a new ID like:
<input type='hidden' name='radsearchHidden' />
and then do the same before the end of .blur:
$("#radsearchHidden").val(radsearch);
I made some changes to your code (http://jsfiddle.net/zdeZ2/2/) which I'll describe below:
<div id="radButton" class="searchBoxRight"></div> I assume you have something in there=> <input id="radButton" class="searchBoxRight" type="button" value="rad button">
I rewrote your validator with blur as follows. As suggested it coroses the radSearch value to an integer before comparisions The changes remove the searchError and searchSuccess classes before validating. I also made some optimizations for you.
//Rad search
$('#radSearch').blur(function () {
//remove classes from previous validating
var $this = $(this).removeClass("searchError").removeClass("searchSuccess");
var radsearch = $this.val() | 0; //radsearch is an integer
if (radsearch < 2 || radsearch > 50) {
$this.addClass("searchError");
radsearchok = 0;
} else {
$this.addClass("searchSuccess");
radsearchok = 1;
}
});
Can be equivalently written as:
//Rad search
$('#radSearch').blur(function () {
var $this = $(this);
var radsearch = $("#radSearch").val() | 0; //radsearch is an integer
var valid = radsearch < 2 || radsearch > 50;
$this.toggleClass("searchError", !valid)
.toggleClass("searchSuccess", valid);
radsearchchok = valid ? 1 : 0;
});

making the checkbox to display div

here am trying to display divs ClinicFieldSet and HospitalFieldset by selecting the given text boxes. If both are selected, both ClinicFieldset and HospitalFieldset should display and if one of the check box is selected it should show which div is selected.
The problem with my script is, when one of the checkboxes are clicked, both checkboxes are getting selected and it is not posible to uncheck them also. So please suggest me an idea to fix this problem :(
I used Javascript onClick in both checkboxes to apply on both of them.
<script type="text/javascript>
var clinic = document.getElementById('clinic');
var visit = document.getElementById('visit');
if((clinic.checked = true) && (visit.checked = true) )
{
document.getElementById('ClinicFieldSet').style.display='block';
document.getElementById('HospitalFieldSet').style.display='block';
}
else if((clinic.checked = true) && (visit.checked = false))
{
document.getElementById('ClinicFieldSet').style.display='block';
document.getElementById('HospitalFieldSet').style.display='none';
}
else if((clinic.checked = false) && (visit.checked = true))
{
document.getElementById('ClinicFieldSet').style.display='none';
document.getElementById('HospitalFieldSet').style.display='block';
}
else
{
document.getElementById('ClinicFieldSet').style.display='none';
document.getElementById('HospitalFieldSet').style.display='none';
}
HTML
<input type="checkbox" name="type" id="clinic" onClick="dispp();" >Clinic Practice
<input type="checkbox" name="type" id="visit" onClick="dispp();" >Visiting Hospital
In your if statement use the == equality operator.
The single = is used to assign a value, not test its equality.
May I suggest a revised approach (not using in-line click-handlers) with a slightly amended html, just to make the JavaScript somewhat more simple:
HTML:
<input type="checkbox" name="type" id="clinic" /><label for="clinic">Clinic Practice</label>
<input type="checkbox" name="type" id="hospital" /><label for="hospital">Visiting Hospital</label>
<div id="clinicInfo">
<h2>Clinic information</h2>
</div>
<div id="hospitalInfo">
<h2>Hospital information</h2>
</div>
JavaScript:
document.getElementById('hospitalInfo').style.display = 'none';
document.getElementById('clinicInfo').style.display = 'none';
var inputs = document.getElementsByTagName('input');
function dispp() {
if (this.checked) {
document.getElementById(this.id + 'Info').style.display = 'block';
}
else {
document.getElementById(this.id + 'Info').style.display = 'none';
}
}
for (i = 0; i < inputs.length; i++) {
if (inputs[i].type.toLowerCase() == 'checkbox') {
inputs[i].onchange = dispp;
}
}
JS Fiddle demo.
Try this
if(clinic.checked == true)
{
document.getElementById('ClinicFieldSet').style.display='block';
}
else
{
document.getElementById('ClinicFieldSet').style.display='none';
}
if(visit.checked == true)
{
document.getElementById('HospitalFieldSet').style.display='block';
}
else
{
document.getElementById('HospitalFieldSet').style.display='none';
}
var form=document.forms.add
form.elements.check.addEventListener('change',function(e) {
e.preventDefault()
var check=document.querySelector('.check')
if(check.checked=true)
{
document.querySelector('.inside').style.display='block'
}
else{
document.querySelector('.inside').style.display='none'
}
})

Categories

Resources