Allow only one checked checkbox, Angular best practice. - javascript

Im using angular.
I have Three checkboxes in a Group and i want to make sure only one of them can be checked. So if one is checked the other two has to bee unchacked. I can Think of doing this several ways with native JS or jQuery but i want to know if there is a typical Angular way of doing it.
Here is Plunker with a set up of the checkboxes and angular controll.
http://plnkr.co/edit/IZmGwktrCaYNyrWjfSqf?p=preview
<body ng-controller="MainCtrl">
<div>
{{vm.Output}}
<br>
<br>
<br>
<label>
<input type="checkbox" name="groupA" ng-model="vm.a1" ng-change="vm.changeGroupA()"> A1 </label>
<label>
<input type="checkbox" name="groupA" ng-model="vm.a2" ng-change="vm.changeGroupA()"> A2 </label>
<label>
<input type="checkbox" name="groupA" ng-model="vm.a3" ng-change="vm.changeGroupA()"> A3 </label>
<br>
<br>
<br> {{vm.Output}}
</body>

Since you can't use radio buttons, I've made this plnkr when you check one the others are deselected:
http://plnkr.co/edit/apSE3cIXA7DIvulBfNGX?p=preview
<label> <input type="checkbox" name="groupA" ng-model="vm.a1" ng-change="vm.a2 = false; vm.a3 = false; vm.changeGroupA()" > A1 </label>
<label> <input type="checkbox" name="groupA" ng-model="vm.a2" ng-change="vm.a1 = false; vm.a3 = false; vm.changeGroupA()" > A2 </label>
<label> <input type="checkbox" name="groupA" ng-model="vm.a3" ng-change="vm.a2 = false; vm.a1 = false; vm.changeGroupA()" > A3 </label>
Hope it helps =)
Edit: You can probably change the state of the other checkboxes in the controller for best practice, made in the html just to demonstrate more quickly..

Another way to do it would be: http://plnkr.co/edit/kH12pYkXfY6t6enrlSns
<br><br><br>
<label> <input type="checkbox" name="groupA" ng-model="vm.groupA[0]" ng-change="vm.changeGroupA(0)" > A1 </label>
<label> <input type="checkbox" name="groupA" ng-model="vm.groupA[1]" ng-change="vm.changeGroupA(1)" > A2 </label>
<label> <input type="checkbox" name="groupA" ng-model="vm.groupA[2]" ng-change="vm.changeGroupA(2)" > A3 </label>
<br><br><br>
The controller would look like this:
$scope.vm = {
groupA: [false, true, false],
count : 0,
changeGroupA : function (index)
{
for (i = 0, len = this.groupA.length; i < len; ++i) {
this.groupA[i] = ((1 << index) & (1 << i)) > 0;
}
this.Output = '(' + this.count + ')' + this.Output;
this.count ++;
},
Output : 'Here we go'
}

You might want to do it the hard way out. http://plnkr.co/edit/A53w4IJMRXQmvRsxa8JA and it should work
changeGroupA : function (x)
{
if (x === 'A1'){
$scope.vm.a1 = true;
$scope.vm.a2 = false;
$scope.vm.a3 = false;
}
else if (x === 'A2') {
$scope.vm.a2 = true;
$scope.vm.a1 = false;
$scope.vm.a3 = false;
}
else if (x === 'A3') {
$scope.vm.a3 = true;
$scope.vm.a1 = false;
$scope.vm.a2 = false;
}
this.Output = '(' + this.count + ')' + this.Output;
this.count ++;
},

This works perfectly fine for angular 6 or 8
HTML:
<div class="custom-control custom-checkbox custom-control-inline">
<input type="checkbox" class="custom-control-input" id="check1id"
[(ngModel)]="check1" (change)="onlyOneValue($event)"/>
<label for="check1id" class="custom-control-label">Checkbox 1</label>
</div>
<div class="custom-control custom-checkbox custom-control-inline">
<input type="checkbox" class="custom-control-input" id="check2id"
[(ngModel)]="check2" (change)="onlyOneValue($event)" />
<label for="check2id" class="custom-control-label"> Checkbox 2 </label>
</div>
.ts code:
check1=false;
check2=false;
onlyOneValue(e)
{
if (e.target.id == "Check1id") {
this.Check1= true;
this.Check2 = false;
}
else if (e.target.id == "Check1id") {
this.Check1= true;
this.Check2 = false;
}
}

Why don't you just use a radio button?
<label>
<input type="radio" name="groupA" ng-model="vm.a1" ng-change="vm.changeGroupA()"> A1 </label>
<label>
<input type="radio" name="groupA" ng-model="vm.a2" ng-change="vm.changeGroupA()"> A2 </label>
<label>
<input type="radio" name="groupA" ng-model="vm.a3" ng-change="vm.changeGroupA()"> A3 </label>

Related

Condition: input:checked with the same class

I would like to have a little help on an enigma that I have.
I have a button that changes according to the number of input:checked
but I would like to add a condition which is: select of the checkboxes of the same class.
for example can I have 2 or more input.
<input class="banana" type="checkbox" value="Cavendish">
<input class="banana" type="checkbox" value="Goldfinger">
<input class="chocolato" type="checkbox" value="cocoa powder">
<input class="chocolato" type="checkbox" value="milk chocolate">
<input class="apple" type="checkbox" value="honneycrisp">
<input class="apple" type="checkbox" value="granny smith">
I can't use attribute name or value. it is not possible to modify the inputs.
the condition:
$('input[type="checkbox"]').click(function(){
if($('input[type="checkbox"]:checked').length >=2){
////////
if (my classes are the same) {
$('#btn').html("click me").prop('disabled', false);
} else {
$('#btn').html("too bad").prop('disabled', true);
}
//////
}
I try with
var checkClass = [];
$.each($("input[type="checkbox"]:checked"), function() {
checkClass.push($(this).attr('class'));
});
I don't know if I'm going the right way or if I'm complicating the code but a little help would be welcome. For the moment my attempts have been unsuccessful.
The following function will reference the first checkbox that's checked className and enable each checkbox that has said className whilst disabling all other checkboxes. Details are commented in Snippet.
// All checkboxes
const all = $(':checkbox');
// Any change event on any checkbox run function `matchCategory`
all.on('change', matchCategory);
function matchCategory() {
// All checked checkboxes
const checked = $(':checkbox:checked');
let category;
// if there is at least one checkbox checked...
if (checked.length > 0) {
// ...enable (.btn)...
$('.btn').removeClass('off');
// ...get the class of the first checked checkbox...
category = checked[0].className;
// ...disable ALL checkboxes...
all.attr('disabled', true);
// ...go through each checkbox...
all.each(function() {
// if THIS checkbox has the class defined as (category)...
if ($(this).is('.' + category)) {
// ...enable it
$(this).attr('disabled', false);
// Otherwise...
} else {
// ...disable and uncheck it
$(this).attr('disabled', true).prop('checked', false);
}
});
// Otherwise...
} else {
// ...enable ALL checkboxes...
all.attr('disabled', false);
// ...disable (.btn)
$('.btn').addClass('off');
}
return false;
}
.off {
pointer-events: none;
opacity: 0.4;
}
<input class="beverage" type="checkbox" value="Alcohol">
<label>🍸</label><br>
<input class="beverage" type="checkbox" value="Coffee">
<label>☕</label><br>
<input class="dessert" type="checkbox" value="cake">
<label>🍰</label><br>
<input class="dessert" type="checkbox" value="Ice Cream">
<label>🍨</label><br>
<input class="appetizer" type="checkbox" value="Salad">
<label>🥗</label><br>
<input class="appetizer" type="checkbox" value="Bread">
<label>🥖</label><br>
<button class='btn off' type='button '>Order</button>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
some thing like that ?
const
bt_restart = document.getElementById('bt-restart')
, chkbx_all = document.querySelectorAll('input[type=checkbox]')
;
var checked_class = ''
;
bt_restart.onclick = _ =>
{
checked_class = ''
chkbx_all.forEach(cbx=>
{
cbx.checked=cbx.disabled=false
cbx.closest('label').style = ''
})
}
chkbx_all.forEach(cbx=>
{
cbx.onclick = e =>
{
if (checked_class === '') checked_class = cbx.className
else if (checked_class != cbx.className )
{
cbx.checked = false
cbx.disabled = true
cbx.closest('label').style = 'color: grey'
}
}
})
<button id="bt-restart">restart</button> <br> <br>
<label> <input class="banana" type="checkbox" value="Cavendish" > a-Cavendish </label> <br>
<label> <input class="banana" type="checkbox" value="Goldfinger" > a-Goldfinger </label> <br>
<label> <input class="chocolato" type="checkbox" value="cocoa powder" > b-cocoa powder </label> <br>
<label> <input class="chocolato" type="checkbox" value="milk chocolate"> b-milk chocolate </label> <br>
<label> <input class="apple" type="checkbox" value="honneycrisp" > c-honneycrisp </label> <br>
<label> <input class="apple" type="checkbox" value="granny smith" > c-granny smith </label> <br>
In fact it's like a Matching Pairs card game
this answer is without global checked_group variable, and respecting epascarello message about data attribute see also usage.
Adding a repentance on uncheck elements
const
bt_restart = document.getElementById('bt-restart')
, chkbx_all = document.querySelectorAll('input[type=checkbox]')
;
function clearGame()
{
chkbx_all.forEach(cbx=>
{
cbx.checked = cbx.disabled = false
cbx.closest('label').style = ''
})
}
bt_restart.onclick = clearGame
chkbx_all.forEach(cbx=>
{
cbx.onclick = e =>
{
let checkedList = document.querySelectorAll('input[type=checkbox]:checked')
if (cbx.checked)
{
let checked_group = ''
checkedList.forEach(cEl=>{ if (cEl !== cbx) checked_group = cEl.dataset.group })
if (checked_group === '') checked_group = cbx.dataset.group
else if (checked_group !== cbx.dataset.group )
{
cbx.checked = false // you need to uncheck wrong group checkboxes for preserving checkedList
cbx.disabled = true
cbx.closest('label').style = 'color: grey'
}
}
else if (checkedList.length === 0) // case of cheked repentir
clearGame()
}
})
<button id="bt-restart">restart</button> <br> <br>
<label> <input data-group="banana" type="checkbox" value="Cavendish" > a-Cavendish </label> <br>
<label> <input data-group="banana" type="checkbox" value="Goldfinger" > a-Goldfinger </label> <br>
<label> <input data-group="chocolato" type="checkbox" value="cocoa powder" > b-cocoa powder </label> <br>
<label> <input data-group="chocolato" type="checkbox" value="milk chocolate"> b-milk chocolate </label> <br>
<label> <input data-group="apple" type="checkbox" value="honneycrisp" > c-honneycrisp </label> <br>
<label> <input data-group="apple" type="checkbox" value="granny smith" > c-granny smith </label> <br>

Check specific radio button is checked

I'm just trying to return true/false in one my my jquery methods depending on the check of a 2 radio buttons and if it's selected or not
I've tried several things but have not been able to get this right, it still submit the form without giving error that the buttons are not selected.
HTML Code
<label class="checkout-item" for="payment_1">Cash On Delivery</label>
<input type="radio" name="payment" class="radio" id="payment_1" value="3" iscod="1" onclick="selectPayment(this)">
<label class="checkout-item" for="payment_2">Credit Card / Debit Card</label>
<input type="radio" name="payment" class="radio" id="payment_2" value="9" checked="" iscod="0" onclick="selectPayment(this)">
<label class="checkout-item" for="ECS_NEEDINSURE_1">Home Delivery</label>
<input name="shipping" type="radio" id="ECS_NEEDINSURE_1" value="3" checked="true" supportcod="1" insure="0" class="radio" onclick="selectShipping(this)">
<label class="checkout-item" for="ECS_NEEDINSURE_2">Self-pickup</label>
<input name="shipping" type="radio" id="ECS_NEEDINSURE_2" value="8" supportcod="1" insure="0" class="radio" onclick="selectShipping(this)">
Javascript
function checkOrderForm(frm) {
var paymentSelected = false;
var shippingSelected = false;
// Check whether the payment method is selected
for (i = 0; i < frm.elements.length; i++) {
if (frm.elements[i].name == 'shipping' && frm.elements[i].checked) {
shippingSelected = true;
}
if (frm.elements[i].name == 'payment' && frm.elements[i].checked) {
paymentSelected = true;
}
}
if (!shippingSelected) {
alert(flow_no_shipping);
return false;
}
if (!paymentSelected) {
alert(flow_no_payment);
return false;
}
If I'm understanding your question correctly, you would only like this test to pass if BOTH of the radio buttons are checked. Currently, as long as one radio button in each group is checked, the code variable will be set to true, ignoring the state of the other radio button.
For example, if ONLY one of your shipping radio buttons was checked, the shippingSelected variable would be set to true and it would remain true.
A way to fix this is to begin with shippingSelected and paymentSelected set to true, and if one of the radio buttons are found to be unchecked, the variable will be set to false.
Here's an example:
var paymentSelected = true;
var shippingSelected = true;
// Check whether the payment method is selected
for (i = 0; i < frm.elements.length; i++) {
if (frm.elements[i].name == 'shipping' && !frm.elements[i].checked) {
shippingSelected = false;
}
if (frm.elements[i].name == 'payment' && !frm.elements[i].checked) {
paymentSelected = false;
}
}
You can use $("#payment_1").checked to check whether the radio is checked or not. Similarly you could use other ID's to check whether they are selected or not.
Here is the fiddle:
https://jsfiddle.net/bf8bo43t/
Try below code,
HTML
<form method="post" name="frm_payment_types">
<label class="checkout-item" for="payment_1">Cash On Delivery</label>
<input type="radio" name="payment" class="radio" id="payment_1" value="3" iscod="1" onclick="selectPayment(this)">
<label class="checkout-item" for="payment_2">Credit Card / Debit Card</label>
<input type="radio" name="payment" class="radio" id="payment_2" value="9" iscod="0" onclick="selectPayment(this)">
<label class="checkout-item" for="ECS_NEEDINSURE_1">Home Delivery</label>
<input name="shipping" type="radio" id="ECS_NEEDINSURE_1" value="3" supportcod="1" insure="0" class="radio" onclick="selectShipping(this)">
<label class="checkout-item" for="ECS_NEEDINSURE_2">Self-pickup</label>
<input name="shipping" type="radio" id="ECS_NEEDINSURE_2" value="8" supportcod="1" insure="0" class="radio" onclick="selectShipping(this)">
<br />
<input type="submit" name="submit" onclick="return checkOrderForm();" />
</form>
Javascript
<script type="text/javascript">
function validateForm(){
var payment_1 = document.getElementById('payment_1');
var payment_2 = document.getElementById('payment_2');
var ECS_NEEDINSURE_1 = document.getElementById('ECS_NEEDINSURE_1');
var ECS_NEEDINSURE_2 = document.getElementById('ECS_NEEDINSURE_2');
if((payment_1.checked == true || payment_2.checked == true) && (ECS_NEEDINSURE_1.checked == true || ECS_NEEDINSURE_2.checked == true)){
return true;
}
else if(payment_1.checked == false && payment_2.checked == false){
alert("Please select Cash On Delivery or Credit Card / Debit Card.");
}
else if(ECS_NEEDINSURE_1.checked == false && ECS_NEEDINSURE_2.checked == false){
alert("Please select Home Delivery or Self-pickup.");
}
return false;
}
</script>

JQuery No radio button checked issue

I have a series of randomly generated textbox and radio-button inputs. It's kinda like a Quiz, so what I would like to do is collect all of the inputs and send them to the server so it can evaluate them.
Now, to make it easier, I put all of the radio-button inputs to the end.
I use the following code to collect the inputs of the textbox-types:
$('#button_submit').click(function() {
var answer_list = '';
$('input:text').each(function(index,data) {
answer_list = answer_list + '$' + $(data).val();
}
...
}
This works perfectly, but after this, I don't know what to do. I could loop through the input:radio:checked elements and add the value of those to my string, which would work perfectly, except if the user decides to submit their answers while leaving one of the radio-button inputs empty. In that case, nothing gets added to the string and the server will be missing the answer to that question and it messes everything up.
So I need to add something to my string when the code realizes that there is a radio-button question, but no answer was chosen, but I have no idea how to do it.
Edit:
HTML example:
<div class="form-group" id="form-group-34">
<label class="control-label " for="question">What is 92848 × 71549?</label>
<input autofocus="true" class="form-control" id="input34" name="answer" size="20" type="text" value="">
</div>
<div class="form-group" id="form-group-35">
<label class="control-label " for="question">Is 194 divisible by 3?</label>
<br><input id="14-answer-0" name="14-answer" type="radio" value="1">
<label for="14-answer-0">Yes</label>
<br><input id="14-answer-1" name="14-answer" type="radio" value="0">
<label for="14-answer-1">No</label>
</div>
<div class="form-group" id="form-group-36">
<label class="control-label " for="question">Determine the day of the week for 1954 Jun 26!</label>
<br><input id="35-answer-0" name="35-answer" type="radio" value="1">
<label for="35-answer-0">Monday</label>
<br><input id="35-answer-1" name="35-answer" type="radio" value="2">
<label for="35-answer-1">Tuesday</label>
<br><input id="35-answer-2" name="35-answer" type="radio" value="3">
<label for="35-answer-2">Wednesday</label>
<br><input id="35-answer-3" name="35-answer" type="radio" value="4">
<label for="35-answer-3">Thursday</label>
<br><input id="35-answer-4" name="35-answer" type="radio" value="5">
<label for="35-answer-4">Friday</label>
<br><input id="35-answer-5" name="35-answer" type="radio" value="6">
<label for="35-answer-5">Saturday</label>
<br><input id="35-answer-6" name="35-answer" type="radio" value="0">
<label for="35-answer-6">Sunday</label>
</div>
But the problem is, that these questions are randomly generated. So there can be 5 simple textbox-type inputs, then 5 radio-button type ones, or there might be only 1 radio-button type question, and all of their attributes are generated dynamically, so I can't really put the radio-button group's name in the code, because I don't know it.
You could use this to see if they are all checked:
var allRadios = $('input[name="namevalue"][type=radio]').length;
var allCheckedRadios $('input[name="namevalue"][type=radio]').filter(function() {
return this.checked;
}).length;
if( allRadios == allCheckedRadios){
// do what you need
}
whatever your name is change "namevalue" to that. The same basic logic to get the values can be applied.
Note: performance gain for modern browsers on these selector forms above over $('input:radio') can be had.
EDIT From updated question:
Here I applied the techniques above to walk through each of the form groups looking for radio buttons, and if they exist throw an alert if none are checked within that group. You could also create and return a Boolean value if ANY of the groups have radio selections with none selected. "hasUncheckedRadios" will be either 0 if none are checked or 1 if one is checked - since radio buttons within a group only select one. You could use this logic in your validation to ensure that all of the groups have a valid checked radio button (IF they contain a radio that is);
function checkRadios() {
var allGroups = $('.form-group');
allGroups.each(function() {
var allRadios = $(this).find('input[type=radio]').length;
var hasUncheckedRadios = $(this).find('input[type=radio]').filter(function() {
return this.checked;
}).length;
console.log('total:' + allRadios + ' checked:' + hasUncheckedRadios);
// if allRadios is > 0 then radios exist and hasUncheckedRadios == 0 none are checked
if (allRadios && !hasUncheckedRadios) {
alert("Form Group" + $(this).attr('id') + " has radio buttons unaswered");
}
});
}
$('#checkem').on('click', function() {
console.log('checking...');
checkRadios();
});
fiddle with it here: https://jsfiddle.net/MarkSchultheiss/nv7cjpr2/
I would iterate a bit more: https://jsfiddle.net/Twisty/ghc7u2ab/
HTML
<div class="form-group" id="form-group-34">
<label class="control-label " for="question">What is 92848 × 71549?</label>
<input autofocus="true" class="form-control" id="input34" name="answer" size="20" type="text" value="">
</div>
<div class="form-group" id="form-group-35">
<label class="control-label " for="question">Is 194 divisible by 3?</label>
<br>
<input id="14-answer-0" name="14-answer" type="radio" value="1">
<label for="14-answer-0">Yes</label>
<br>
<input id="14-answer-1" name="14-answer" type="radio" value="0">
<label for="14-answer-1">No</label>
</div>
<div class="form-group" id="form-group-36">
<label class="control-label " for="question">Determine the day of the week for 1954 Jun 26!</label>
<br>
<input id="35-answer-0" name="35-answer" type="radio" value="1">
<label for="35-answer-0">Monday</label>
<br>
<input id="35-answer-1" name="35-answer" type="radio" value="2">
<label for="35-answer-1">Tuesday</label>
<br>
<input id="35-answer-2" name="35-answer" type="radio" value="3">
<label for="35-answer-2">Wednesday</label>
<br>
<input id="35-answer-3" name="35-answer" type="radio" value="4">
<label for="35-answer-3">Thursday</label>
<br>
<input id="35-answer-4" name="35-answer" type="radio" value="5">
<label for="35-answer-4">Friday</label>
<br>
<input id="35-answer-5" name="35-answer" type="radio" value="6">
<label for="35-answer-5">Saturday</label>
<br>
<input id="35-answer-6" name="35-answer" type="radio" value="0">
<label for="35-answer-6">Sunday</label>
</div>
<button id="button_submit">Submit</button>
JQuery
$("#button_submit").click(function() {
var answer_list = {};
$(".form-group").each(function(i, v) {
console.log("Index:", i, "ID: [", $(v).attr("id"), "]");
answer_list[$(v).attr("id")] = {};
var ind = $(v).find("input");
$.each(ind, function(i2, el) {
console.log("Type of Element:", $(el).attr("type"));
switch ($(el).attr("type")) {
case "text":
answer_list[$(v).attr("id")][$(el).attr("id")] = ($(el).val() != "") ? $(el).val() : null;
break;
case "radio":
var isAnswered = false;
$(el).each(function(i3, rad) {
if ($(rad).is(":checked")) {
answer_list[$(v).attr("id")][$(rad).attr("name")] = $(rad).val();
isAnswered = true;
}
if (!isAnswered) {
answer_list[$(v).attr("id")][$(el).eq(0).attr("name")] = null;
}
});
break;
}
});
});
console.log(answer_list);
return false;
});
Possible Result
answer_list: {
form-group-34: {
input34: null
},
form-group-35: {
14-answer: 0
},
form-group-36: {
35-answer: null
}
}
This will iterate each group and look for an answer. If one is found, the value is added. If not, null is added as the result.
loop class group that has radio then use .prop("checked")
var frmGroup= 0, checked= 0;
$('.form-group').each(function(index) {
if ($(this).children('input:radio').length > 0) {
frmGroup++;
$(this).children('input:radio').each(function(index) {
if ($(this).prop("checked") == true) {
checked++;
}
});
}
});
if(frmGroup != checked)...
working example: https://jsfiddle.net/nsL3drz5/

Check All checkbox should be unchecked

function toggle(source) {
checkboxes = document.getElementsByName('options[]');
for (var i = 0, n = checkboxes.length; i < n; i++) {
checkboxes[i].checked = source.checked;
}
}
<form class="unsubscribe_form" action="process.php" method="post">
<input type="checkbox" class="unsubscribe-checkbox" name="options[]" id="checkbox-1-1" value="Option1">
<label for="checkbox-1-1"></label>Option 1
<input type="checkbox" class="unsubscribe-checkbox" name="options[]" id="checkbox-1-2" value="Option2">
<label for="checkbox-1-2"></label>Option 2
<input type="checkbox" class="unsubscribe-checkbox" name="options[]" id="checkbox-1-3" value="Option2">
<label for="checkbox-1-3"></label>Option 3
<input type="checkbox" class="unsubscribe-checkbox" name="options[]" id="checkbox-1-4" value="Option3">
<label for="checkbox-1-4"></label>Option 4
<input type="checkbox" class="unsubscribe-checkbox" name="options[]" id="checkbox-1-5" value="Option3">
<label for="checkbox-1-5"></label>Option 5
<input type="checkbox" class="unsubscribe-checkbox" id="checkbox-1-6" value="All" onClick="toggle(this)" />
<label for="checkbox-1-6"></label>All
<br>
<input type="submit" name="formSubmit" value="Unsubscribe" />
</form>
When I check the All checkbox, of course, it will mark all the checkboxes, but once I uncheck one checkbox, the All checkbox is still checked. This should be unchecked. How should I do that using JS?
You will need to add onchange event handlers to every checkbox and check inside if the "All" checkbox should be checked (all checkboxes are selected) or unchecked (at least one is deselected). For example like this:
var checkboxes = [].slice.call(document.getElementsByName('options[]')),
allCheckbox = document.querySelector('input[value="All"]');
checkboxes.forEach(function(checkbox) {
checkbox.onchange = function() {
if (!this.checked) {
allCheckbox.checked = false;
}
else {
var checked = checkboxes.filter(function(check) {
return check.checked;
});
if (checked.length === checkboxes.length) {
allCheckbox.checked = true;
}
}
};
});
function toggle(source) {
for (var i = 0, n = checkboxes.length; i < n; i++) {
checkboxes[i].checked = source.checked;
}
}
<form class="unsubscribe_form" action="process.php" method="post">
<input type="checkbox" class="unsubscribe-checkbox" name="options[]" id="checkbox-1-1" value="Option1">
<label for="checkbox-1-1"></label>Option 1
<input type="checkbox" class="unsubscribe-checkbox" name="options[]" id="checkbox-1-2" value="Option2">
<label for="checkbox-1-2"></label>Option 2
<input type="checkbox" class="unsubscribe-checkbox" name="options[]" id="checkbox-1-3" value="Option2">
<label for="checkbox-1-3"></label>Option 3
<input type="checkbox" class="unsubscribe-checkbox" name="options[]" id="checkbox-1-4" value="Option3">
<label for="checkbox-1-4"></label>Option 4
<input type="checkbox" class="unsubscribe-checkbox" name="options[]" id="checkbox-1-5" value="Option3">
<label for="checkbox-1-5"></label>Option 5
<input type="checkbox" class="unsubscribe-checkbox" id="checkbox-1-6" value="All" onClick="toggle(this)" />
<label for="checkbox-1-6"></label>All
</form>
Note that I converted checkboxes collection to array with [].slice.call in order to use convenient array methods. Simple for loops can be used instead.
I'd suggest the following:
function toggle() {
// getting a reference to all the 'name="option[]" elements:
var options = document.getElementsByName('options[]'),
// a reference to the 'all' checkbox:
all = document.getElementById('checkbox-1-6');
// if the changed checkbox is the 'all':
if (this === all) {
// we iterate over all the options checkboxes (using
// Array.prototype.forEach()):
Array.prototype.forEach.call(options, function(checkbox) {
// and we set their checked property to the checked property
// state of the 'all' checkbox:
checkbox.checked = all.checked;
});
} else {
// otherwise we set the 'all' checkbox to the state of
// the Boolean returned by Array.prototype.every(),
// which returns true if all checkboxes evaluate to
// the condition within the function, otherwise false:
all.checked = Array.prototype.every.call(options, function(checkbox) {
return checkbox.checked;
});
}
}
// getting a NodeList of all the elements of 'class="unsubscribe-checkbox"':
var options = document.querySelectorAll('.unsubscribe-checkbox');
// iterating over them, again with Array.prototype.forEach()
// and assigning a change event-listener, which will execute the
// name function:
Array.prototype.forEach.call(options, function(opt) {
opt.addEventListener('change', toggle);
});
function toggle() {
var options = document.getElementsByName('options[]'),
all = document.getElementById('checkbox-1-6');
if (this === all) {
Array.prototype.forEach.call(options, function(checkbox) {
checkbox.checked = all.checked;
});
} else {
all.checked = Array.prototype.every.call(options, function(checkbox) {
return checkbox.checked;
});
}
}
var options = document.querySelectorAll('.unsubscribe-checkbox');
Array.prototype.forEach.call(options, function(opt) {
opt.addEventListener('change', toggle);
});
<form class="unsubscribe_form" action="process.php" method="post">
<input type="checkbox" class="unsubscribe-checkbox" name="options[]" id="checkbox-1-1" value="Option1">
<label for="checkbox-1-1"></label>Option 1
<input type="checkbox" class="unsubscribe-checkbox" name="options[]" id="checkbox-1-2" value="Option2">
<label for="checkbox-1-2"></label>Option 2
<input type="checkbox" class="unsubscribe-checkbox" name="options[]" id="checkbox-1-3" value="Option2">
<label for="checkbox-1-3"></label>Option 3
<input type="checkbox" class="unsubscribe-checkbox" name="options[]" id="checkbox-1-4" value="Option3">
<label for="checkbox-1-4"></label>Option 4
<input type="checkbox" class="unsubscribe-checkbox" name="options[]" id="checkbox-1-5" value="Option3">
<label for="checkbox-1-5"></label>Option 5
<input type="checkbox" class="unsubscribe-checkbox" id="checkbox-1-6" value="All" />
<label for="checkbox-1-6"></label>All
<br>
<input type="submit" name="formSubmit" value="Unsubscribe" />
</form>
You may notice that I've removed the onClick attribute from the 'all' checkbox, in preference of unobtrusive JavaScript, where the event-handlers are assigned via the JavaScript itself (which ordinarily makes for more easily-maintained code, as the arguments to be passed to a given function are assigned in the code itself, rather than having to be separately updated in the HTML).
References:
Array.prototype.every().
Array.prototype.forEach().
document.getElementsByName().
document.getElementById().
document.querySelectorAll().
EventTarget.addEventListener().
Function.prototype.call().

Max and min allowed or limited checkbox

I want to limit how many checkbox clicked. When it reaches to the limit I want to trigger an action. Let's say max limit is 3 and min limit is 1. Here's my html.
<div class="ingredients">
<span class="border-bottom"></span>
<div class="row cf">
<label tabindex="1" class="mnf-checkbox" for="tuzCheck">
<span class="ck"></span>
<input id="tuzCheck" type="checkbox"
name="information" value="1" />
<span class="name">Tuz</span>
</label>
<label tabindex="2" class="mnf-checkbox" for="karnibaharCheck">
<span class="ck"></span>
<input id="karnibaharCheck" type="checkbox"
name="information" value="2" />
<span class="name">Karnıbahar</span>
</label>
<label tabindex="3" class="mnf-checkbox" for="biberCheck">
<span class="ck"></span>
<input id="biberCheck" type="checkbox"
name="information" value="3" />
<span class="name">Biber</span>
</label>
<label tabindex="4" class="mnf-checkbox" for="sosisCheck">
<span class="ck"></span>
<input id="sosisCheck" type="checkbox"
name="information" value="4" />
<span class="name">Sosis</span>
</label>
<label tabindex="5" class="mnf-checkbox" for="prasaCheck">
<span class="ck"></span>
<input id="prasaCheck" type="checkbox"
name="information" value="5" />
<span class="name">Prasa</span>
</label>
</div>
</div>
I tried to use this code but that doesn't help me.
var maxCheckedCount = 3;
jQuery('input[type=checkbox]').click(function () {
var n = jQuery('input:checked').length;
if (n >= maxCheckedCount) {
$(this).prop('checked', false);
$(".counter").text("hakkın kalmadı :(").css("color", "#cd1212");
}
});
What I want to do is: when it reaches its limit I want to trigger an action and the user can't continue to check. I'm beginner so please don't judge me :)
Try this one...
http://jsfiddle.net/ZpqQ2/3/
var max = 3;
jQuery('input[type=checkbox]').click(function () {
var n = jQuery('input:checked').length;
if (n > max) {
// here your code
$(this).prop('checked', false);
alert('Minimum of 3');
}
});
try the Fiddle
jQuery('input[type=checkbox]').click(function() {
var n = jQuery('input[type=checkbox]:checked').length;
if (n >= 1 && n <= 3) {
// here your code
}
});
var countChecked = function () {
var n = $("input:checked").length;
alert("n>>>" + n);
$("div").text(n + (n === 1 ? " is" : " are") + " checked!");
if(n == 2){
$("input:checkbox:not(:checked)").attr("disabled", true);
} else {
$("input:checkbox:not(:checked)").attr("disabled", false);
}
};
countChecked();
$("input[type=checkbox]").on("click", countChecked);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p>
<input type="checkbox" name="newsletter" class="newsletter" value="Hourly">
<input type="checkbox" name="newsletter" class="newsletter" value="Daily">
<input type="checkbox" name="newsletter" class="newsletter" value="Weekly">
<input type="checkbox" name="newsletter" class="newsletter" value="Monthly" >
<input type="checkbox" name="newsletter" class="newsletter" value="Yearly">
</p>
The problem is I still contunie to check after an alert. That doesn't restrict me to check.

Categories