I have a set of checkboxes, and validation such that at least one of those checkboxes need to be checked on submit. But I want to be able to set a validation error if the user blurs out of the set of checkboxes. The problem is that if I do a blur for the last one it doesn't work because they could be shift-tabbing to the second from last checkbox. I've tried to but the onblur in the fieldset tag, but that didn't trigger a blur at all. Is this just a limitation that can't be overcome with plain html and vanilla JS?
You can look at what the next element that is focused is and determine if they are under the same grouping.
document.querySelectorAll('input[type="checkbox"]').forEach((elem) => {
elem.addEventListener("blur", function (event) {
const nextElem = event.relatedTarget;
const fieldSet = elem.closest('fieldset');
const isValid = fieldSet.querySelector("input:checked") !== null;
if (nextElem?.closest('fieldset') !== fieldSet) {
fieldSet.classList.toggle("error", !isValid);
} else if (isValid) {
fieldSet.classList.remove("error");
}
});
});
.error {
color: red;
}
<form>
<fieldset>
<legend>Pizza One</legend>
<input type="checkbox" name="x1-1" id="x1-1">
<label for="x1-1">Cheese</label>
<input type="checkbox" name="x1-2" id="x1-2">
<label for="x1-2">Peppers</label>
<input type="checkbox" name="x1-3" id="x1-3">
<label for="x1=3">Mushrooms</label>
</fieldset>
<fieldset>
<legend>Pizza Two</legend>
<input type="checkbox" name="x2-1" id="x2-1">
<label for="x2-1">Cheese</label>
<input type="checkbox" name="x2-2" id="x2-2">
<label for="x2-2">Peppers</label>
<input type="checkbox" name="x2-3" id="x2-3">
<label for="x2-3">Mushrooms</label>
</fieldset>
<input type="submit" />
</form>
Adding in a trick to use HTML5 validation
document.querySelectorAll('input[type="checkbox"]').forEach((elem) => {
elem.addEventListener("blur", function(event) {
const nextElem = event.relatedTarget;
const fieldSet = elem.closest('fieldset');
const isValid = fieldSet.querySelector("input:checked") !== null;
if (nextElem?.closest('fieldset') !== fieldSet) {
fieldSet.classList.toggle("error", !isValid);
}
});
elem.addEventListener("change", function(event) {
const fieldSet = elem.closest('fieldset');
const isValid = fieldSet.querySelector("input:checked") !== null;
if (isValid) {
fieldSet.classList.remove("error");
fieldSet.querySelectorAll("input").forEach((cb) => {
cb.removeAttribute("required");
});
} else {
fieldSet.querySelectorAll("input").forEach((cb) => {
cb.setAttribute("required", "required");
});
}
});
const changeEvt = document.createEvent("HTMLEvents");
changeEvt.initEvent("change", false, true);
elem.dispatchEvent(changeEvt);
});
.error {
color: red;
}
<form>
<fieldset>
<legend>Pizza One</legend>
<input type="checkbox" name="x1-1" id="x1-1">
<label for="x1-1">Cheese</label>
<input type="checkbox" name="x1-2" id="x1-2">
<label for="x1-2">Peppers</label>
<input type="checkbox" name="x1-3" id="x1-3">
<label for="x1=3">Mushrooms</label>
</fieldset>
<fieldset>
<legend>Pizza Two</legend>
<input type="checkbox" name="x2-1" id="x2-1">
<label for="x2-1">Cheese</label>
<input type="checkbox" name="x2-2" id="x2-2">
<label for="x2-2">Peppers</label>
<input type="checkbox" name="x2-3" id="x2-3">
<label for="x2-3">Mushrooms</label>
</fieldset>
<input type="submit" />
</form>
Based on epascarello's suggestion I was able to create a function that provided similar functionality to the one provided. I have an error span that's underneath the checkboxes. I wanted behavior that would immediately remove that if any checkbox was checked, but only add the error span if the user blurred out of the entire set of checkboxes. Note that there is only one fieldset on this page, and the error span has an specific id I could reference. Here's the function that I got working:
document.querySelectorAll('input[type="checkbox"]').forEach((elem) => {
elem.addEventListener("blur", function (event) {
var errorSpan = document.getElementById("checkboxesErrorSpan");
var isValid = document.querySelector("fieldset").querySelectorAll("input:checked").length > 0;
if (isValid) {
if ((errorSpan.style.display == "inline")) {
errorSpan.style.display = "none";
}
}
else {
if (event.relatedTarget.type != "checkbox") {
if ((errorSpan.style.display == "none")) {
errorSpan.style.display = "inline";
}
}
}
});
});
Related
I want to remove the disabled attribute from the button when each field is filled out.
My code works when a single input is filled.
What am i doing wrong here?
Here are the HTML and JS
checkInput()
function checkInput() {
let input = document.querySelectorAll('.form-control')
const button = document.querySelector('.submit-btn')
input.forEach(function (e) {
let disabled = true;
e.addEventListener('keyup', function () {
if (e.value !== '') {
disabled = false
} else {
disabled = true
return false
}
if(disabled) {
button.setAttribute('disabled', 'disabled')
} else {
button.removeAttribute('disabled')
}
})
})
}
<div class="form-group">
<label for="name">Name*</label>
<input class="form-control" type="text" id="name" placeholder="Name">
</div>
<div class="form-group">
<label for="lastName">lastName*</label>
<input class="form-control" type="text" id="lastName" placeholder="lastName">
</div>
<div class="form-group">
<label for="fiscalCode">fiscalCode*</label>
<input class="form-control" type="text" id="fiscalCode" placeholder="fiscalCode">
</div>
<button type="submit" disabled="disabled" class="submit-btn">Continue</button>
It does not work because you want to have all inputs affect the state of a button, yet you only check one variable for adding/removing disabled property.
Here is a working code snippet with an example where i created an array of properties, one for each input, that i can refer to in every fired key up event
checkInput()
function checkInput() {
let input = document.querySelectorAll('.form-control')
const button = document.querySelector('.submit-btn')
const disabled = Array(input.length).fill(true);
input.forEach(function (e, index) {
e.addEventListener('input', function () {
disabled[index] = e.value === ''; // simplified if/else statement of yours
if(disabled.some(Boolean)) {
button.setAttribute('disabled', 'disabled')
} else {
button.removeAttribute('disabled')
}
})
})
}
<div class="form-group">
<label for="name">Name*</label>
<input class="form-control" type="text" id="name" placeholder="Name">
</div>
<div class="form-group">
<label for="lastName">lastName*</label>
<input class="form-control" type="text" id="lastName" placeholder="lastName">
</div>
<div class="form-group">
<label for="fiscalCode">fiscalCode*</label>
<input class="form-control" type="text" id="fiscalCode" placeholder="fiscalCode">
</div>
<button type="submit" disabled="disabled" class="submit-btn">Prosegui</button>
Additionaly stoping the function execution when assigning disabled = true in the first else statement is also a wrong approach, as you most likely want to not only assign the disable value, but also the disabled property of the button.
EDIT: as mentioned in the comment by CID it is reasonable to change the event listener to input so we can handle the copying and pasting events as well
You are adding a keyup event for each input field.
that event only checks the current input field if it is empty or not.
it does not check the 3 input fields itself
this should do the trick:
checkInput()
function checkInput() {
let input = document.querySelectorAll('.form-control')
const button = document.querySelector('.submit-btn')
input.forEach(function (e) {
let disabled = true;
e.addEventListener('keyup', function () {
const emptyFields = Array.from(input).filter( input => input.value === "");
disabled = emptyFields.length > 0;
if(disabled) {
button.setAttribute('disabled', 'disabled')
} else {
button.removeAttribute('disabled')
}
})
})
}
You are enabling the submit button on keyup event of any 3 inputs. So it gets enabled on any 3 inputs.
Remove the return on disabled flow to disable button after clearing.
checkInput()
function checkInput() {
let input = document.querySelectorAll('.form-control')
const button = document.querySelector('.submit-btn')
input.forEach(function (e) {
let disabled = true;
e.addEventListener('keyup', function () {
if (e.value !== '') {
disabled = false
} else {
disabled = true
// return false <-- this makes function exit before your disable button
}
if(disabled) {
button.setAttribute('disabled', 'disabled')
} else {
button.removeAttribute('disabled')
}
})
})
}
<div class="form-group">
<label for="name">Name*</label>
<input class="form-control" type="text" id="name" placeholder="Name">
</div>
<div class="form-group">
<label for="lastName">lastName*</label>
<input class="form-control" type="text" id="lastName" placeholder="lastName">
</div>
<div class="form-group">
<label for="fiscalCode">fiscalCode*</label>
<input class="form-control" type="text" id="fiscalCode" placeholder="fiscalCode">
</div>
<button type="submit" disabled="disabled" class="submit-btn">Continue</button>
Another solution is to check if all inputs are filled out on every change in any input.
addHandlers();
// Return true if all fields are not empty
function areAllFieldsFilledOut() {
let inputs = document.querySelectorAll('.form-control');
let result = true;
inputs.forEach(e => {
if (e.value === "")
result = false;
});
return result;
}
// Add keyup event handlers to all input fields
function addHandlers() {
let inputs = document.querySelectorAll('.form-control');
const button = document.querySelector('.submit-btn');
inputs.forEach(e => {
// On each change in any input, check if all inputs are
// not empty, and if true, enable the button
e.addEventListener('keyup', e => {
let result = areAllFieldsFilledOut();
if (result) {
button.removeAttribute('disabled');
} else {
button.setAttribute('disabled', 'disabled');
}
});
});
}
<div class="form-group">
<label for="name">Name*</label>
<input class="form-control" type="text" id="name" placeholder="Name">
</div>
<div class="form-group">
<label for="lastName">lastName*</label>
<input class="form-control" type="text" id="lastName" placeholder="lastName">
</div>
<div class="form-group">
<label for="fiscalCode">fiscalCode*</label>
<input class="form-control" type="text" id="fiscalCode" placeholder="fiscalCode">
</div>
<button type="submit" disabled="disabled" class="submit-btn">Prosegui</button>
Here is my answer:
function checkInput() {
document.querySelectorAll('input').forEach(input => {
input.addEventListener('keyup', function () {
let emptyFieldsCount = Array.from(input).filter(input => input.value == "").length;
if (emptyFieldsCount > 0) {
button.setAttribute('disabled', 'disabled')
} else {
button.removeAttribute('disabled')
}
})
});
}
i need to check if checkbox 1 or 2 is clicked.
error : only background is printing while clicking any checbox and pressing button
function onlyOne(checkbox) {
var checkboxes = document.getElementsByName('check')
checkboxes.forEach((item) => {
if (item !== checkbox) item.checked = false;
});
}
function run() {
var checkboxes = document.getElementsByName('check')
if (document.getElementById('c1').checked) {
alert("background");
} else if (document.getElementById('c1').checked) {
alert("foreground");
}
}
<input type="checkbox" name="check" id="c1" value="background" onclick="onlyOne(this)">background</input>
<input type="checkbox" name="check" id="c2" value="foreground" onclick="onlyOne(this)">foreground</input>
<input type="button" value="button" onclick="run()">
In the second statment you write c1 again instead of c2
function onlyOne(checkbox) {
var checkboxes = document.getElementsByName('check')
checkboxes.forEach((item) => {
if (item !== checkbox) item.checked = false;
});
}
function run() {
var checkboxes = document.getElementsByName('check')
if (document.getElementById('c1').checked) {
alert("background");
} else if (document.getElementById('c2').checked) {
alert("foreground");
}
}
<input type="checkbox" name="check" id="c1" value="background" onclick="onlyOne(this)">background</input>
<input type="checkbox" name="check" id="c2" value="foreground" onclick="onlyOne(this)">foreground</input>
<input type="button" value="button" onclick="run()">
Instead of use your method why don't use radio and print the radio checked like:
document.getElementById('run').addEventListener('click',AlertMe);
function AlertMe() {
document.getElementsByName('check').forEach( (el) =>{
if(el.checked === true) alert(el.value);
});
}
<input type="radio" name="check" value="background">background</input>
<input type="radio" name="check" value="foreground">foreground</input>
<input type="button" value="button" id='run'>
It's miss named ID of element for foreground
function run(){
[...]
else if(document.getElementById('c1').checked){
alert("foreground");
[...]
it should be:
[...]
else if(document.getElementById('c2').checked){
alert("foreground");
[...]
I have 2 radio button, each valued Yes and No respectively and 1 textbox.. If I checked on No button, the input textbox will open. If checked on Yes, textbox will disabled.
This code is working fine but I want to delete content that input to the textbox if the user checked Yes
function ismcstopu() {
var chkNo = document.getElementById("radio2_ismcstop");
var mcnostopreason = document.getElementById("mcnostopreason");
mcnostopreason.disabled = chkNo.checked ? false : true;
if (!mcnostopreason.disabled) {
mcnostopreason.focus();
} else {
mcnostopreason.val('');
}
}
<input type="radio" class="form-check-input" id="radio1_ismcstop" name="ismcstop" onclick="ismcstopu()" value="Yes">Yes
<input type="radio" class="form-check-input" id="radio2_ismcstop" name="ismcstop" onclick="ismcstopu()" value="No">No
<label for="mcnostopreason">If No, Reason:</label>
<input class="inputstyle-100" type="text" id="mcnostopreason" name="mcnostopreason" value="" disabled>
.val is a jQuery construct but you are using DOM
Here is a better version using eventListener
Change the document.getElementById("container") to whatever container you have (your form for example)
Note: It is often better to test true than to test false
I also added labels to the radios so we can click the yes or no too
document.getElementById("container").addEventListener("click", function(e) {
const tgt = e.target;
if (tgt.name === "ismcstop") {
const mcnostopreason = document.getElementById("mcnostopreason");
mcnostopreason.disabled = tgt.value === "Yes";
if (mcnostopreason.disabled) {
mcnostopreason.value = '';
} else {
mcnostopreason.focus();
}
}
})
<div id="container">
<label><input type="radio" class="form-check-input" id="radio1_ismcstop" name="ismcstop" value="Yes">Yes</label>
<label><input type="radio" class="form-check-input" id="radio2_ismcstop" name="ismcstop" value="No">No</label>
<label for="mcnostopreason">If No, Reason:
<input class="inputstyle-100" type="text" id="mcnostopreason" name="mcnostopreason" value="" disabled>
</label>
</div>
jQuery version
$("[name=ismcstop]").on("click", function() {
if (this.name === "ismcstop") {
const $mcnostopreason = $("#mcnostopreason");
$mcnostopreason.prop("disabled", this.value === "Yes");
if ($mcnostopreason.is(":disabled")) {
$mcnostopreason.val("");
} else {
$mcnostopreason.focus();
}
}
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<label><input type="radio" class="form-check-input" id="radio1_ismcstop" name="ismcstop" value="Yes">Yes</label>
<label><input type="radio" class="form-check-input" id="radio2_ismcstop" name="ismcstop" value="No">No</label>
<label for="mcnostopreason">If No, Reason:
<input class="inputstyle-100" type="text" id="mcnostopreason" name="mcnostopreason" value="" disabled>
</label>
mcnostopreason is not a jQuery object. therefore you could do: var mcnostopreason = $("#mcnostopreason");
Or you could just change mcnostopreason.val('') to mcnostopreason.value = '' ( this will mean you don't need to change anything else)
I have 5 checkboxes, I want to tick 1 checkbox then the other 4 checkboxes will disable to tick, if I untick the 1 checkbox, the other 4 checkboxes will able to tick. Hope someone can guide me on how to solve it based on my below the coding:
<div class="form-group" id="taraf_keselamatan_fail">
<label for="cp1" class="control-label col-lg-4">Taraf Keselamatan Fail:</label>
<div class="col-lg-3">
<input type="checkbox" name="rahsia_besar" id="rahsia_besar" value="1"><b> Rahsia Besar</b></input>
<input type="checkbox" name="rahsia" id="rahsia" value="1"><b> Rahsia</b></input>
<input type="checkbox" name="sulit" id="sulit" value="1"><b> Sulit</b></input> <br>
<input type="checkbox" name="terhad" id="terhad" value="1"><b> Terhad</b></input>
<input type="checkbox" name="terbuka" id="terbuka" value="1"><b> Terbuka</b></input>
</div>
</div>
Now my output result like below the picture can tick all the checkboxes:
My expected result like below the sample picture, just can tick 1 box in the checkbox.
This is my try the coding in the javascript, but it cannot work:
<script>
var form = document.getElementById("checkForm");
form.onclick = delegateFormClick;
addChangeHandlers(form);
function addChangeHandlers(form)
{
for(var i=0;i<form.elements.length;i++)
{
var element = form.elements[i];
if(element.tagName === "INPUT" && element.type === "checkbox")
{
if(!element.onchange)
{
element.onchange = checkBoxChanged;
}
}
}
}
function delegateFormClick(evt)
{
var target;
if(!evt)
{
//Microsoft DOM
target = window.event.srcElement;
}else if(evt)
{
//w3c DOM
target = evt.target;
}
if(target.nodeType === 1 && target.tagName === "INPUT" && target.type === "checkbox")
{
if(target.checked)
{
disableCheckBoxes(target.id, document.getElementById("checkForm"));
}else if(!target.checked)
{
enableCheckBoxes(document.getElementById("checkForm"));
}
}
}
function checkBoxChanged()
{
if(this.checked)
{
disableCheckBoxes(this.id, document.getElementById("checkForm"));
}else if(!this.checked)
{
enableCheckBoxes(document.getElementById("checkForm"));
}
}
function disableCheckBoxes(id, form)
{
var blacklist = [];
if(id)
{
switch(id)
{
case "rahsia_besar":
blacklist = ["rahsia", "sulit","terhad","terbuka"];
break;
case "rahsia":
blacklist = ["rahsia_besar", "sulit","terhad","terbuka"];
break;
case "sulit":
blacklist = ["rahsia_besar", "rahsia","terhad","terbuka"];
break;
case "terhad":
blacklist = ["rahsia_besar", "rahsia","sulit","terbuka"];
break;
case "terbuka":
blacklist = ["rahsia_besar", "rahsia","sulit","terhad"];
break;
}
}else
{
throw new Error("id is needed to hard-wire input blacklist");
}
for(var i=0;i<blacklist.length;i++)
{
var element = document.getElementById(blacklist[i]);
if(element && element.nodeType === 1)
{
//check for element
if(element.tagName === "INPUT" && element.type === "checkbox" && !element.checked)
{
element.disabled = "disabled";
}
}else if(!element || element.nodeType !== 1)
{
throw new Error("input blacklist item does not exist or is not an element");
}
}
}
function enableCheckBoxes(form)
{
for(var i=0;i<form.elements.length;i++)
{
var element = form.elements[i];
if(element.tagName === "INPUT" && element.type === "checkbox" && !element.checked)
{
element.disabled = "";
}
}
}
</script>
The intended behavior does (almost ... see EDIT) not need any form of additional scripting for one gets such a behavior for free with any radio group ...
// scripting is just for proofing the behavior of a radio group/collection
function logCurrentlyCheckedFailValue(evt) {
if (evt.target.type === 'radio') {
console.log(`radio name: ${ evt.target.name }\nradio value: ${ evt.target.value }`);
}
}
function mainInit() {
document
.querySelector('#taraf_keselamatan_fail')
.addEventListener('click', logCurrentlyCheckedFailValue)
}
mainInit();
.as-console-wrapper { max-height: 60%!important; }
<form>
<fieldset class="form-group" id="taraf_keselamatan_fail">
<legend class="control-label col-lg-4">Taraf Keselamatan Fail:</legend>
<div class="col-lg-3">
<label>
<input type="radio" name="taraf_keselamatan_fail" value="rahsia_besar"/>
<b>Rahsia Besar</b>
</label>
<label>
<input type="radio" name="taraf_keselamatan_fail" value="rahsia"/>
<b>Rahsia</b>
</label>
<label>
<input type="radio" name="taraf_keselamatan_fail" value="sulit"/>
<b>Sulit</b>
</label>
<label>
<input type="radio" name="taraf_keselamatan_fail" value="terhad"/>
<b>Terhad</b>
</label>
<label>
<input type="radio" name="taraf_keselamatan_fail" value="terbuka"/>
<b>Terbuka</b>
</label>
</div>
</fieldset>
</form>
EDIT
I want to apologize to the OP because of me not reading the question carefully enough. The OP's use case indeed is distinct from what a radio group actually does offer.
Here we go ...
function setControlStateViaBoundConfig(elm) {
const config = this;
if (elm !== config.ignore) {
elm.checked = config.checked;
elm.disabled = config.disabled;
}
}
function toggleBehaviorOfFailureOptions(evt) {
const targetElement = evt.target;
if (targetElement.type === 'checkbox') {
const isDisableOthers = targetElement.checked;
evt.currentTarget // equals element with `id="taraf_keselamatan_fail"`
.querySelectorAll('[type="checkbox"]')
.forEach(setControlStateViaBoundConfig, {
ignore: targetElement,
checked: false,
disabled: isDisableOthers,
});
}
}
function mainInit() {
document
.querySelector('#taraf_keselamatan_fail')
.addEventListener('click', toggleBehaviorOfFailureOptions)
}
mainInit();
[type="checkbox"]:disabled + b { opacity: .4; }
.as-console-wrapper { max-height: 60%!important; }
<form>
<fieldset class="form-group" id="taraf_keselamatan_fail">
<legend class="control-label col-lg-4">Taraf Keselamatan Fail:</legend>
<div class="col-lg-3">
<label>
<input type="checkbox" name="rahsia_besar" value="1"/>
<b>Rahsia Besar</b>
</label>
<label>
<input type="checkbox" name="rahsia" value="1"/>
<b>Rahsia</b>
</label>
<label>
<input type="checkbox" name="sulit" value="1"/>
<b>Sulit</b>
</label>
<label>
<input type="checkbox" name="terhad" value="1"/>
<b>Terhad</b>
</label>
<label>
<input type="checkbox" name="terbuka" value="1"/>
<b>Terbuka</b>
</label>
</div>
</fieldset>
</form>
I created a Stackblitz from you code extract and it is working, could you please check if this is what you expected as solution ?
I wrote some code which sums up all the values of checkboxes with a "toggle all" option. At the beginning I needed to only have information about the value, but now I need to have sum inside an input element, but it does not work.
NOTICE: I know ID can be used only once! I put both input and span to show that it works with span and not with input.
// Shorter querySelectorAll that returns a real array.
function select(selector, parent) {
return Array.from((parent || document).querySelectorAll(selector));
}
var inputs = select('.sum'),
totalElement = document.getElementById('payment-total')
function sumUpdate() {
totalElement.innerHTML = inputs.reduce(function(result, input) {
return result + (input.checked ? parseFloat(input.value) : 0);
}, 0).toFixed(2);
}
// Update the sums in function on input change.
inputs.forEach(function(input) {
input.addEventListener("change", sumUpdate);
});
select(".checkAll").forEach(function(checkAll) {
var targetFieldSet = document.getElementById(checkAll.getAttribute("data-target-set"));
var targetInputs = select(".sum", targetFieldSet);
// Update checkAll in function of the inputs on input change.
targetInputs.forEach(function(input) {
input.addEventListener("change", function() {
checkAll.checked = input.checked && targetInputs.every(function(sibling) {
return sibling.checked;
});
});
});
// Update the inputs on checkall change, then udpate the sums.
checkAll.addEventListener("change", function() {
targetInputs.forEach(function(input) {
input.checked = checkAll.checked;
});
sumUpdate();
});
});
function checkInput(text) {
if (text) {
$("#clearBtn1").addClass("show");
} else {
$("#clearBtn1").removeClass("show");
}
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<p><label><input type="checkbox" class="checkAll" data-target-set="setA"/> Check all Set A</label></p>
<fieldset id="setA">
<legend>Set A Books</legend>
<input value="300" type="checkbox" class="sum" data-toggle="checkbox"> English
<input value="500" type="checkbox" class="sum" data-toggle="checkbox"> Science
<input value="755" type="checkbox" class="sum" data-toggle="checkbox"> Christian Living
</fieldset>
<p></p>
<div class="card-charge-info">
Price: <input type="text" id="payment-total" value="" disabled/></div> <br/> Price: <span id="payment-total">0</span>
</div>
I done some modification to your sumUpdate function making it working now, you need to give the input control and the span different id:
// Shorter querySelectorAll that returns a real array.
function select(selector, parent) {
return Array.from((parent || document).querySelectorAll(selector));
}
var values = document.querySelectorAll('.sum');
function sumUpdate() {
var total = 0;
var selectedItems = Array.prototype.filter.call(values,function(input) {
return input.checked ? input : null;
});
$(selectedItems).each(function (index, element) {
total = total + parseFloat($(element).val());
});
total = parseFloat(total).toFixed(2);
$('#payment-total').val(total);
$('#payment-total-span').text(total);
}
// Update the sums in function on input change.
values.forEach(function(input) {
input.addEventListener("change", sumUpdate);
});
select(".checkAll").forEach(function(checkAll) {
var targetFieldSet = document.getElementById(checkAll.getAttribute("data-target-set"));
var targetInputs = select(".sum", targetFieldSet);
// Update checkAll in function of the inputs on input change.
targetInputs.forEach(function(input) {
input.addEventListener("change", function() {
checkAll.checked = input.checked && targetInputs.every(function(sibling) {
return sibling.checked;
});
});
});
// Update the inputs on checkall change, then udpate the sums.
checkAll.addEventListener("change", function() {
targetInputs.forEach(function(input) {
input.checked = checkAll.checked;
});
sumUpdate();
});
});
function checkInput(text) {
if (text) {
$("#clearBtn1").addClass("show");
} else {
$("#clearBtn1").removeClass("show");
}
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<p><label><input type="checkbox" class="checkAll" data-target-set="setA"/> Check all Set A</label></p>
<fieldset id="setA">
<legend>Set A Books</legend>
<input value="300" type="checkbox" class="sum" data-toggle="checkbox"> English
<input value="500" type="checkbox" class="sum" data-toggle="checkbox"> Science
<input value="755" type="checkbox" class="sum" data-toggle="checkbox"> Christian Living
</fieldset>
<p></p>
<div class="card-charge-info">
Price: <input type="text" id="payment-total" value="" disabled/> <br/> Price: <span id="payment-total-span">0</span>
</div>