Checkboxes not being checked programmatically after user checks it once - javascript

I'm having an interesting problem I can't solve with a Vue app I'm working on. The behaviour I want (parent checkbox when (un)checked, (un)checks all child checkboxes) is there, but with a problem.
When you click a checkbox, that checkbox is ignored by parent checkboxes. This means that after clicking any child checkbox, clicking a parent checkbox has no effect on the previously clicked checkbox; it just keeps it's value.
Here's where it gets weird: I looked at the elements tab in safari, and it says the clicked box is changing values when the parent is (un)selected, but visually it is staying the same.
I know that the box is checked, since other parts of the app are doing what I expect, but I can't figure out why it will say a box has class="checked" checked="checked", but still be visually unchecked.
Is there something else that happens to a checkbox when you click it, that makes the way I check child checkboxes visually incorrect?
Relevant HTML:
<template>
<div v-for=“(foo, bar) in foobar” :key=bar>
<div class=“root”>
<input id='checkbox' type="checkbox" class="checked" checked="checked" #click=“handleRootClick($event)">
</div>
<div class=“child 1”>
<div v-for=“(foo, bar) in foobar” :key=bar>
<div class=“child 1 header">
<input id='checkbox' type="checkbox" class="checked" checked="checked" #click=“handleChild1Click($event)">
</div>
<div class=“child 1”>
<div v-if=“foobar.length > 0">
<div class=“child 2 header">
<input id='checkbox' type="checkbox" class="checked" checked="checked" #click=“handleChild2Click($event)">
</div>
<div class="resource-dropdown-contents">
<div v-for=“(foo, bar) in foobar” :key=bar>
<div class=“child 3 header">
<input id='checkbox' type="checkbox" class="checked" checked="checked" #click=“handleChild3Click($event)">
</div>
<div class="compute-dropdown-contents">
<div v-for=“(foo, bar) in foobar” :key=bar>
<div class=“child 4 header">
<input id='checkbox' type="checkbox" class="checked" checked="checked" #click=“handleChild4Click($event)">
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
And here is the relevant typescript code:
public handleRootClick(e) {
const root = e.currentTarget.parentElement.parentElement;
const checkboxes = root.querySelectorAll('#checkbox');
const isChecked = checkboxes[0].classList.contains('checked');
if (isChecked) {
// ensure all children are unchecked
for (let i = 0; i < checkboxes.length; i++) {
if (checkboxes[i].classList.contains('checked')) {
checkboxes[i].classList.remove('checked');
checkboxes[i].removeAttribute('checked');
}
}
} else {
// ensure all children are checked
for (let i = 0; i < checkboxes.length; i++) {
if (!checkboxes[i].classList.contains('checked')) {
checkboxes[i].classList.add('checked');
checkboxes[i].setAttribute('checked', 'checked');
}
}
}
e.stopPropagation();
}
The other handleChildxClick functions are very similar to the above function.

Related

WordPress: Allow to only check one checkbox in a fieldset

I'm using Gravity Forms and the quiz add-on to build a survey.
Every question should have only one accepted answer. But all answers should be "correct".
The quiz add-on works in a different way. It allows only one correct answer for radio buttons. I couldn't limit checkboxes to only one answer.
So I guess I have to work with custom JavaScript to allow only one answer or checked box per fieldset.
The fieldset for a question looks like this:
<fieldset id="field_3_1" class="gfield" data-field-class="gquiz-field">
<legend class="gfield_label gfield_label_before_complex">Question 1</legend>
<div class="ginput_container ginput_container_checkbox">
<div class="gfield_checkbox" id="input_3_1">
<div class="gchoice gchoice_3_1_1">
<input class="gfield-choice-input" name="input_1.1" type="checkbox" value="gquiz21dc402fa" id="choice_3_1_1">
<label for="choice_3_1_1" id="label_3_1_1">Answer 1</label>
</div>
<div class="gchoice gchoice_3_1_2">
<input class="gfield-choice-input" name="input_1.2" type="checkbox" value="gquiz3414cb0c0" id="choice_3_1_2">
<label for="choice_3_1_2" id="label_3_1_2">Answer 2</label>
</div>
<div class="gchoice gchoice_3_1_3">
<input class="gfield-choice-input" name="input_1.3" type="checkbox" value="gquiz21d0214b9" id="choice_3_1_3">
<label for="choice_3_1_3" id="label_3_1_3">Answer 3</label>
</div>
</div>
</div>
</fieldset>
It's not clear how many fieldsets/questions are present at the end. So I need a flexible solution.
I found some JS Code here:
$(function () {
$('input[type=checkbox]').click(function () {
var chks = document.getElementById('<%= chkRoleInTransaction.ClientID %>').getElementsByTagName('INPUT');
for (i = 0; i < chks.length; i++) {
chks[i].checked = false;
}
if (chks.length > 1)
$(this)[0].checked = true;
});
});
But I'm not sure how to adapt it for my use case
This script will make each checkbox per fieldset exclusive.
jQuery(function($) {
$('fieldset input[type="checkbox"]').on('change', function() {
// Set the checkbox just checked.
let just_checked = $(this);
// Get all of the checkboxes in the fieldset.
let all_checkboxes = just_checked.closest('fieldset').find('input[type="checkbox"]');
$.each(all_checkboxes, function(i, v) { // Loop through each of the checkboxes.
if (just_checked.prop('id') === $(v).prop('id')) {
// Check the one just checked.
$(v).prop('checked', true);
} else {
// Uncheck the others.
$(v).prop('checked', false);
}
})
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<fieldset id="field_3_1" class="gfield" data-field-class="gquiz-field">
<legend class="gfield_label gfield_label_before_complex">Question 1</legend>
<div class="ginput_container ginput_container_checkbox">
<div class="gfield_checkbox" id="input_3_1">
<div class="gchoice gchoice_3_1_1">
<input class="gfield-choice-input" name="input_1.1" type="checkbox" value="gquiz21dc402fa" id="choice_3_1_1">
<label for="choice_3_1_1" id="label_3_1_1">Answer 1</label>
</div>
<div class="gchoice gchoice_3_1_2">
<input class="gfield-choice-input" name="input_1.2" type="checkbox" value="gquiz3414cb0c0" id="choice_3_1_2">
<label for="choice_3_1_2" id="label_3_1_2">Answer 2</label>
</div>
<div class="gchoice gchoice_3_1_3">
<input class="gfield-choice-input" name="input_1.3" type="checkbox" value="gquiz21d0214b9" id="choice_3_1_3">
<label for="choice_3_1_3" id="label_3_1_3">Answer 3</label>
</div>
</div>
</div>
</fieldset>
An alternative solution could be to use radio buttons, and use css to make them look like checkboxes. But UX says that checkboxes shouldn't be used as radio buttons, and vice versa. For whatever that's worth.

`alert` Error When Changing Variable Value

I have radio buttons that alert a different number depending on which one is selected.
var radioButtons = document.querySelectorAll('input[type=radio]');
var chanceoflive1 = 0;
var user;
function choose(choice){
user = choice;
}
function changechanceoflive1(){
if (user == 'bricks') {
chanceoflive1 = 1;
}
else if (user == 'wood') {
chanceoflive1 =3
}
else if (user == 'stone') {
chanceoflive1 = 2
}
alert(chanceoflive1);
}
<div id="radiobuttons" class="container" name="buttons" align=center>
<h2>I Want my Building to be Made of:</h2>
<ul>
<li>
<input type="radio" id="brick-option" name="material" value="1" onClick="choose('bricks')" checked="checked">
<label for="brick-option">Bricks</label>
<div class="check"></div>
</li>
<li>
<input type="radio" id="wood-option" name="material" value="3" onClick="choose('wood')">
<label for="wood-option">Wood</label>
<div class="check">
<div class="inside"></div>
</div>
</li>
<li>
<input type="radio" id="stone-option" name="material" value="2" onClick="choose('stone')">
<label for="stone-option">Stone</label>
<div class="check">
<div class="inside"></div>
</div>
</li>
</ul>
</div>
<form action="chooseheight.html">
<div class="wrapper">
<button class="button" onClick="changechanceoflive1()" align=center>Submit</button>
</div>
</form>
When I click wood, it alerts 3, which is perfect. When I click stone, it alerts 2, which is great. Although, when I click bricks, it alerts 0. Why?
Change line 2 to be
var chanceoflive1 = 1;
and all will work as expected. The initial radio button is preselected. Without clicking away from bricks and then back to bricks, chanceoflive1 remains as its initial value of 0.
That's because the user haven't actually chosen anything if he doesn't click on any of the checkbox. Since you want to make bricks the default option, you can call choose('bricks') at the end of your script, or just set var user = 'bricks'; in the variable declaration.

Can I set a checkbox to be enabled or disabled based on whether multiple checkboxes are checked?

So I have multiple row of check boxes like the picture below
I want to make the add,edit and delete checkbox in the same row be disabled when the most left checkbox in the same row is checked using jquery, i try using solution in here solution, but this solution only work for 1 group of checboxes, i'm gonna have a lot of checkboxes group, i prefer using loop statement for this case, but i cant come up with any solution.
here's my html code:
<div class="row">
<div class="col-sm-5"><input type="checkbox" name="aauth100" value="auth100" id="auth100" onclick ="togAuth1()">New Member + Kit Purchase</input></div>
<div class="col-sm-2"><input type="checkbox" name="aaddAuth100" value="addAuth100" id="addAuth100">Add</input></div>
<div class="col-sm-2"><input type="checkbox" name="aeditAuth100" value="editAuth100" id="editAuth100">Edit</input></div>
<div class="col-sm-2"><input type="checkbox" name="adelAuth100" value="delAuth100" id="delAuth100">Delete</input></div>
</div>
<div class="row">
<div class="col-sm-5"><input type="checkbox" name="auth101" value="auth101" id="auth101">New Member Registration</input></div>
<div class="col-sm-2"><input type="checkbox" name="addAuth101" value="addAuth101" id="addAuth101">Add</input></div>
<div class="col-sm-2"><input type="checkbox" name="editAuth101" value="editAuth101" id="editAuth101">Edit</input></div>
<div class="col-sm-2"><input type="checkbox" name="delAuth101" value="delAuth101" id="delAuth101">Delete</input></div>
</div>
<div class="row">
<div class="col-sm-5"><input type="checkbox" name="auth102" value="auth102" id="auth102">Member Data Maintenance</input></div>
<div class="col-sm-2"><input type="checkbox" name="addAuth102" value="addAuth102" id="addAuth102">Add</input></div>
<div class="col-sm-2"><input type="checkbox" name="editAuth102" value="editAuth102" id="editAuth102">Edit</input></div>
<div class="col-sm-2"><input type="checkbox" name="delAuth102" value="delAuth102" id="delAuth102">Delete</input></div>
</div>
<div class="row">
<div class="col-sm-5"><input type="checkbox" name="auth103" value="auth103" id="auth103">Member Registration Listing</input></div>
<div class="col-sm-2"><input type="checkbox" name="addAuth103" value="addAuth103" id="addAuth103">Add</input></div>
<div class="col-sm-2"><input type="checkbox" name="editAuth103" value="editAuth103" id="editAuth103">Edit</input></div>
<div class="col-sm-2"><input type="checkbox" name="delAuth103" value="delAuth103" id="delAuth103">Delete</input></div>
</div>
<div class="row">
<div class="col-sm-5"><input type="checkbox" name="auth104" value="auth104" id="auth104">Geneology Listing</input></div>
<div class="col-sm-2"><input type="checkbox" name="addAuth104" value="addAuth104" id="addAuth104">Add</input></div>
<div class="col-sm-2"><input type="checkbox" name="editAuth104" value="editAuth104" id="editAuth104">Edit</input></div>
<div class="col-sm-2"><input type="checkbox" name="delAuth104" value="delAuth104" id="delAuth104">Delete</input></div>
</div>
<div class="row">
<div class="col-sm-5"><input type="checkbox" name="auth105" value="auth105" id="auth105">Member Rank Report</input></div>
<div class="col-sm-2"><input type="checkbox" name="addAuth105" value="addAuth105" id="addAuth105">Add</input></div>
<div class="col-sm-2"><input type="checkbox" name="editAuth105" value="editAuth105" id="editAuth105">Edit</input></div>
<div class="col-sm-2"><input type="checkbox" name="delAuth105" value="delAuth105" id="delAuth105">Delete</input></div>
</div>
You can assign some class to your checkbox. Then use the .each() method of jquery this way.
$(".someclass").each(function(){
if($(this).is(':checked'))
{
// Disable other checkbox in row
}
else
{
//don't disable checkbox
}
})
This will loop through all the checkbox with the assigned class and you can easily separate the checkbox of left row with class.
Though you will have to find a way, how to target other checkbox at right side in the same row.
One way you can do this is to to use each row. Then from there select the first div and get it's input. That can be used for the change event, which then you can disable all but the first checkbox:
$('.row').each(function(){
var self = this;
$(this).find('div:first input').change(function(){
// disables all but the first input in the div rows
if(this.checked) $(self).find('div:gt(0) input').attr("disabled", true);
else $(self).find('div:gt(0) input').attr("disabled", false);
});
});
Demo
This single line of code does the trick, in a change event:
$('.col-sm-5').on('change', function(){
$(this).nextAll('.col-sm-2').children('input').prop('disabled',
$(this).children('input').prop('checked'));
});
I'll break it down:
$('.col-sm-5').on('change', ...
Whenever an element with the col-sm-5 class (or one of its children) changes...
$(this).nextAll('.col-sm-2') ...
Get all the following siblings of this (the element that changed) which have the class col-sm-2 ...
.children('input') ...
Get the input elements that are children of the above...
.prop('disabled', ...
The disabled property will be set to either true or false ...
$(this).children('input') ...
Get the input box that is contained in the div with the class col-sm-5 that just changed ...
.prop('checked') ...
Find out if it's checked or not. So,
$(this).children('input').prop('checked')
evaluates to either true or false, and we're plugging it into this:
.prop('disabled', [true or false])
So, if the first checkbox is checked, the next three are disabled, and if it isn't, they aren't.

Javascript check bootstrap checkbox by id

I have the following form :
<form class="form-inline" role="form">
<div class="col-xs-3">
<div class="pic-container">
<div class="checkbox">
<label>
<input type="checkbox" name="discounting" onchange='handleChange(this);' id='check11' > Show only price-discounted products
</label>
</div>
</div>
</div>
<div class="col-xs-3">
<div class="pic-container">
<div class="checkbox" id='check21'>
<label>
<input type="checkbox" name="discounting" onchange='' id='check21'> Show only price-discounted products
</label>
</div>
</div>
</div>
</form>
I'd like to be able to check the second checkbox automatically with JavaScript once I check the first one. I tried using the following script :
<script>
function handleChange(cb) {
if(cb.checked == true) {
alert('Message 1');
document.getElementById("check21").checked = true;
} else {
alert('Message 2');
var x = document.getElementById("check21").disabled= false;
}
}
</script>
But it doesn't work since I think with bootstrap is a question of classes.
The problem as Didier pointed out is that you have two elements with the same ID:
<div class="checkbox" id='check21'>
and
<input type="checkbox" name="discounting" onchange='' id='check21'>
The call to document.getElementById('check21') will probably (because the behavior is undefined) return the first one, which in this case is the <div> element, not the checkbox.
You must not use the same ID on two HTML elements, so you need to change the ID on one or the other of them.
http://jsfiddle.net/uywaxds5/2/
I included boostrap as an external reference.
<div class="checkbox" id='check22'>
<label>
<input type="checkbox" name="discounting" onchange='' id='check21'> Show only price-discounted products
</label>
</div>
Fixing the duplicate id seems to work.
If it does not works, the issue might be in another part of your code.
Use a different name for the second radio button
<input type="checkbox" name="discounting21">
There can only be one selected radio button belonging to the same group(ie. name).

Angular ng-model changes to undefined when checkbox on ng-repeat has the required attribute

I have an array of applications. A subset of that array is pushed into another array.
$scope.applicant.selectedApps = [];
$scope.applicant.applications = applications;
angular.forEach(applications, function (application) {
if(application.isSelected){
$scope.applicant.selectedApps .push(application);
}
}
I know have 2 ng-repeats that loop over those arrays:
<div class="row">
<div class="form-group col-sm-10 col-sm-offset-1">
<div class="radio">
<label>
<input type="radio" name="intent" ng-model="applicant.intent" value="Y" required />YES
</label>
</div>
<div class="row" ng-show="applicant.intent == 'Y'">
<div class="col-xs-11 col-xs-offset-1">
<div class="row" ng-repeat="app in applicant.selectedApps">
<div class="col-sm-11 col-sm-offset-1">
<div class="checkbox">
<label>
<input id="Prog{{app.appid}}" name="Progs" type="checkbox" ng-model="app.isSelected" ng-change="appChange(app)" ng-required="applicant.intent == 'Y'" />
{{app.Objective}} - {{app.Name}} - {{app.Description}}
</label>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
<div class="row">
<div class="form-group col-sm-10 col-sm-offset-1">
<div class="radio">
<label>
<input type="radio" name="intent" ng-model="applicant.intent" value="N" required />NO
</label>
</div>
<div class="row" ng-show="applicant.intent == 'N'">
<div class="col-xs-11 col-xs-offset-1">
<div class="row" ng-repeat="dApp in applicant.applications">
<div class="col-sm-11 col-sm-offset-1">
<div class="checkbox">
<label>
<input id="dProg{{dApp.appid}}" name="dProgs" type="checkbox" ng-model="dApp.isSelected" ng-change="dProgChange(dApp)" ng-required="applicant.intent == 'N' && appCount <= 0" />
{{dApp.Objective}} - {{dApp.Name}} - {{dApp.Description}}
</label>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
the two change functions are as followed:
$scope.dProgChange = function (app) {
if (app.isSelected) {
$scope.appCount++;
} else {
$scope.appCount--;
}
};
$scope.ProgChange = function (app) {
if (app.isSelected) {
$scope.selectedAppCount++;
} else {
$scope.selectedAppCount--;
}
};
What i observe is that every app that was initializes with "isSelected" = false will be set to undefined as soon as the radio button is switched to "NO". When switched back to "YES" is selected switches back to false.
This causes the dProgChange to trigger every time the Radio button value changes.
I can't figure out why the "isSelected" switches to undefined.
UPDATE
While trying to create a simplified example, i noticed that the problem occurs as soon as the checkbox is required.
In the plunker listed bellow, the model value for the checkbox is set to undefined as soon as the checkbox is unchecked. That seems to me the same issue i am having.
http://plnkr.co/edit/SBsdew8tzWdNgNOf6W1c?p=info
This is the way AngularJS (ng-model and NgModelController) is supposed to work.
NgModelController has two properties: $viewValue (value entered by user) and $modelValue (value bound to your model). When the value entered by the user fails validation, NgModelController sets the model to undefined.
In AngularJS 1.3, they added the ng-model-options directive. It lets you configure how/when the model gets updated. You can use the allowInvalid option to prevent your model from being set to undefined:
<input type="checkbox"
ng-model="myModel.value"
ng-model-options="{allowInvalid: true}">
So, I am going to add to this answer for future reference. This applies to <input> also. If you have something such as
<input ng-model="speaker.vrange" ng-blur= "updateSpkV()" type="number" data-placement="right" min ="0" max="10"/>
then you will have an invalid input if you set the value to something outside of the range and the model variable will be set to undefined. This became an issue with me when I directly entered an out of bound value rather than using up/down arrows for adjusting a value.

Categories