Remove Associated Checkbox Values from Array - javascript

I have (2) checkboxes: 1) Numbers, 2) Countries. When you check either of these checkboxes an associated form appears: (Associated Number -> 1, 2, 3) and (Associated Countries -> Nigeria, Morocco, Sierra Leone). When you check any checkboxes in these associated forms all the checked values get pushed in an array called “checkedValues.”
How can I specifically remove the associated values of 1) Numbers (1, 2, 3) OR 2) Countries ("Nigeria", "Morocco", "Sierra Leone") from the checkedValeus array, when 1) Numbers or 2) Countries from the Main Category is unchecked?
For example, if Numbers in main category is unchecked remove all its associated values from the checkedValues array.
const numbersForm = document.querySelector('.numbers');
const countriesForm = document.querySelector('.countries');
const numbersCheckbox = document.querySelector('#numbersCheckbox');
const countriesCheckbox = document.querySelector('#countriesCheckbox');
let checkedValues = [];
numbersCheckbox.addEventListener('change', (e) => {
if (numbersCheckbox.checked) {
numbersForm.style.display = 'block'
} else {
numbersForm.style.display = 'none'
}
})
countriesCheckbox.addEventListener('change', (e) => {
if (countriesCheckbox.checked) {
countriesForm.style.display = 'block'
} else {
countriesForm.style.display = 'none'
}
})
// Push checked values to table
const numbers = document.querySelectorAll('.num');
const country = document.querySelectorAll('.country');
const values = document.querySelectorAll('.values')
const pushToTable = function (e, form) {
if (e.target.checked) {
form.push(e.target.value)
console.log(form)
}
else {
form.splice(form.indexOf(e.target.value), 1);
console.log(form)
}
}
numbers.forEach(function (sample) {
sample.addEventListener('change', (e) => pushToTable(e, checkedValues))
});
country.forEach(function (sample) {
sample.addEventListener('change', (e) => pushToTable(e, checkedValues))
});
function uncheckAllNum() {
numbersCheckbox.addEventListener("change", (e) => {
for (let i = 0; i < numbers.length; i++) {
if (!e.target.checked) {
numbers[i].checked = e.target.checked;
numbers[i].dispatchEvent(new Event("change"))
}
}
})
};
uncheckAllNum()
function uncheckAllCountries() {
countriesCheckbox.addEventListener("change", (e) => {
for (let i = 0; i < country.length; i++) {
if (!e.target.checked) {
country[i].checked = e.target.checked;
country[i].dispatchEvent(new Event("change"))
}
}
})
};
uncheckAllCountries()
.numbers {
display: none
}
.countries {
display: none
}
<div class="categories">
<h2>Main Categories</h2>
<input type="checkbox" id="numbersCheckbox">Numbers
<br>
<input type="checkbox" id="countriesCheckbox">Countries
</div>
<div class="numbers">
<h3>Associated Numbers</h3>
<input class="num values" type="checkbox" value=1> 1
<br>
<input class="num values" type="checkbox" value=2> 2
<br>
<input class="num values" type="checkbox" value=3> 3
</div>
<div class="countries">
<h3>Associated Countries</h3>
<input class="country values" type="checkbox" value="Nigeria"> Nigeria
<br>
<input class="country values" type="checkbox" value="Morroco"> Morroco
<br>
<input class="country values" type="checkbox" value="Sierra Leone"> Sierra Leone
</div>

First of All, for in both uncheckAllNum and uncheckAllCountries, I don't see any need to put that logic inside functions as long as you are only executing them once from the same code, and if you intend to use it later you'll have a problem where you keep adding unnecessary event listeners for the same element that all do the same job.
Secondly, You can use the same event listener to handle toggling the display of the forms and updating the checked status of the checkboxes. This will help to minimize your code and make it neater.
Finally, you don't need to keep track of the toggled checkboxes, you can make use of the :checked pseudo-class and document.querySelectorAll().
You can do something like this to get all the checked checkboxes:
document.querySelectorAll('.country:checked, .num:checked')
And if you need to get the values of all checked items, you can do something like this:
const getChecked = () =>
[...document.querySelectorAll('.country:checked, .num:checked')].map(
element => element.value
)
Where it uses the spread syntax [...value] to transform the NodeList to an array which allows the use the .map() function to map each checkbox element to its value.
You can use getChecked () to get an array of the values of selected checkboxes instead of checkedValues in your code.
A working example with refactored javascript code: Example on jsFiddle

Related

Display value of multiple selected checkboxes [duplicate]

This question already has answers here:
Getting multiple values from checked checkboxes Javascript
(3 answers)
Closed 3 months ago.
I am trying to display multiple checkbox values in a separate DIV to show the results of the checkboxes to the user. But I also want to remove the value if the user de-selects the checkbox. This is the code I have so far but can only display/hide one value at a time. For example, if I click checkboxes a, b, and c, it will show all values. But If I uncheck, they will hide. Thanks
<input onchange="selectArr(this)" type="checkbox" name="accessory" value="a"/>
<input onchange="selectArr(this)" type="checkbox" name="accessory" value="b"/>
<input onchange="selectArr(this)" type="checkbox" name="accessory" value="c"/>
<div id="acc"></div>
function selectAcc(cb) {
var x = cb.checked ? cb.value : '';
document.getElementById("acc").innerHTML = x;
}
// selecting input type checkboxes
const inputCheckBoxes = document.querySelectorAll("input[type=checkbox]");
const main = document.querySelector("#main");
// function to print in main div
const printCheckedValue = (array) => {
main.innerText = "";
array.forEach(value => {
main.innerText += value;
})
}
// to store checkboxed values
let checkedValue = [];
// looping through all inputcheckboxes and attching onchange event
Object.values(inputCheckBoxes).forEach((inputCheckBoxe, index) => {
inputCheckBoxe.onchange = (e) => {
// checking if value is checkedbox or not
if (checkedValue.includes(e.target.value)) {
// if checkeboxed than filtering array
checkedValue = checkedValue.filter(val => val != e.target.value)
printCheckedValue(checkedValue);
} else {
checkedValue.push(e.target.value);
printCheckedValue(checkedValue);
}
}
})
<input type="checkbox" name="accessory" value="a" />
<input type="checkbox" name="accessory" value="b" />
<input type="checkbox" name="accessory" value="c" />
<div id="main"></div>
Hope this works for you .
function selectAcc(cb) {
// get previous div value
var previousValue = document.getElementById("acc").getAttribute('value');
var newValue = previousValue;
//store the new clicked value
var value = cb.value;
// if the new value is checked and the value is not present in the div add it to the div string value
if (cb.checked && !previousValue.includes(value)) newValue+=value ;
// else remove the value from div string value
else previousValue = newValue.replace(value, '');
// update new value in div
document.getElementById("acc").innerHTML = newValue;
}
Try put like something this
var checked = []
function selectAcc(cb) {
if(cb.checked){
checked.push(cb.value)
} else {
var index = checked.indexOf(cb.value)
checked.splice(index, 1)
}
document.getElementById("acc").innerHTML = checked.join(' ');
}

How to show div, if one of the checkboxes is checked (with a different name on each checkbox)?

I am trying to show div if one of the two checkboxes is checked. I found it in some article but with the same name, I am using a different name for each checkbox to store it into mysql. My current javascript code is
document.addEventListener('change', function(jj) {
function jj() {
if ((document.getElementById('jj1_ikk').checked) || (document.getElementById('jj2_ikk').checked)) {
document.getElementById('jsa').style.display="block";
} else {
document.getElementById('jsa').style.display="none";
}
}
})
the input fields are
<input type="checkbox" id="jj1_ikk" name="jj1_ikk" /><label for="jj1_ikk">A</label>
<input type="checkbox" id="jj2_ikk" name="jj2_ikk" /><label for="jj2_ikk">B</label>
where jj1_ikk and jj2_ikk are the checkboxes id, and jsa is the div that I want to do show/hide.
I hope my description is clear, thank you.
You can put two check box in span and check changes onclick span like this
HTML
<span onclick="CheckChanges()">
<input type="checkbox" id="jj1_ikk" name="jj1_ikk" /><label for="jj1_ikk">A</label>
<input type="checkbox" id="jj2_ikk" name="jj2_ikk" /><label for="jj2_ikk">B</label>
</span>
<div id="jsa">This is the element that will be shown if both checkboxes aren't checked</div>
JavaScript
var aCheckBox = document.getElementById("jj1_ikk")
var bCheckBox = document.getElementById("jj2_ikk")
function CheckChanges() {
if (aCheckBox.checked == true || bCheckBox.checked == true) {
document.getElementById("jsa").style.display = "block"
} else {
document.getElementById("jsa").style.display = "none"
}
}
You did a mistake when adding the handler for the change event defining two nested functions. Plus I added the event handler only once the document was loaded. You can test the code in this snippet:
//when the document has been loaded, adds the event handlers to the checkboxes
document.addEventListener("DOMContentLoaded", () => {
document.addEventListener('change', () => addHandlers());
});
/**
* Adds handler for the change event on both checkboxes
*/
function addHandlers(){
let jj1 = document.getElementById('jj1_ikk');
let jj2 = document.getElementById('jj2_ikk');
jj1.addEventListener('change', updateMsgVisibility);
jj2.addEventListener('change', updateMsgVisibility);
}
/**
* Show/Hide #jsa based on checkboxes status
*/
function updateMsgVisibility(){
let jj1 = document.getElementById('jj1_ikk');
let jj2 = document.getElementById('jj2_ikk');
if ( (jj1 && (jj1.checked)) || (jj2 && (jj2.checked)) ) {
document.getElementById('jsa').style.display="block";
} else {
document.getElementById('jsa').style.display="none";
}
}
<input type="checkbox" id="jj1_ikk" name="jj1_ikk" /><label for="jj1_ikk">A</label>
<input type="checkbox" id="jj2_ikk" name="jj2_ikk" /><label for="jj2_ikk">B</label>
<div id="jsa" style="display:none;">This is the element that will be shown if both checkboxes aren't checked</div>

Getting multiple value of checkbox in jQuery

I'm trying to get the multiple value of my checkbox with the jQuery but with my code I got double value.
If I pick Apple and Manggo and when I submit the form I get value of Apple Apple Manggo.
A lot of tutorial use .click function. Since I have more function I want to use it outside the const submit =() =>{}
How do I fix this multiple value ?
let fruit_temp = [];
$('input[name="chk_fruit"]').change(function() {
$('input[name="chk_fruit"]:checked').each(function() {
fruit_temp.push($(this).val());
});
});
const submit = () => {
let formData = new FormData();
//more formData
formData.append('Fruit', fruit_temp);
for (var pair of formData.entries()) {
console.log(pair[0] + ', ' + pair[1]);
}
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="col-lg-6 mb-30">
<label><b>Favourite Fruit</b></label><br>
<div class="form-group">
<ul>
<li><input type="checkbox" name="chk_fruit" value="Apple"> Apple</li>
<li><input type="checkbox" name="chk_fruit" value="Manggo"> Manggo</li>
<li><input type="checkbox" name="chk_fruit" value="Honeydew"> Honeydew</li>
<li><input type="checkbox" name="chk_fruit" value="Orange"> Orange</li>
</ul>
<!-- more form field -->
<button onclick="submit()">Submit</button>
</div>
</div>
When you loop through using .each, you are grabbing all of the values that are currently selected and pushing them into the fruit_temp array. However, you are not resetting the value of fruit_temp, so you are pushing more and more with each checkbox. All you you need to do is clear the array with each change:
let fruit_temp = [];
$('input[name="chk_fruit"]').change(function() {
fruit_temp = [];
$('input[name="chk_fruit"]:checked').each(function() {
fruit_temp.push($(this).val());
});
});
let fruit_temp = [];
$('input[name="chk_fruit"]').change(function() {
fruit_temp = []; // reset your variable before adding another checked items
$('input[name="chk_fruit"]:checked').each(function() {
fruit_temp.push($(this).val());
});
});
Simply reset your variable before adding latest checked items into your array. fruit_temp = []; on your change event will do the work.

Removing value from array according to index using splice()

I have 4 checkboxes. I add values of them to an array on check. It looks like this.
Here are the four checkboxes I have.
<input type="checkbox" value="degree">
<input type="checkbox" value="pgd">
<input type="checkbox" value="hnd">
<input type="checkbox" value="advdip">
Once I check all four of them, the array becomes,
["degree", "pgd", "hnd", "advdip"]
When I uncheck a checkbox, I need to remove the value of it from the array according to its correct index number. I used splice() but it always removes the first index which is degree. I need to remove the value from the array according to its index number no matter which checkbox I unselect. Hope someone helps. Below is the code. Thanks in advance!
<input type="checkbox" value="degree">
<input type="checkbox" value="pgd">
<input type="checkbox" value="hnd">
<input type="checkbox" value="advdip">
<script>
function getLevels() {
// get reference to container div of checkboxes
var con = document.getElementById('course-levels');
// get reference to input elements in course-levels container
var inp = document.getElementsByTagName('input');
// create array to hold checkbox values
var selectedValues = [];
// collect each input value on click
for (var i = 0; i < inp.length; i++) {
// if input is checkbox
if (inp[i].type === 'checkbox') {
// on each checkbox click
inp[i].onclick = function() {
if ($(this).prop("checked") == true) {
selectedValues.push(this.value);
console.log(selectedValues);
}
else if ($(this).prop("checked") == false) {
// get index number
var index = $(this).index();
selectedValues.splice(index, 1);
console.log(selectedValues);
}
}
}
}
}
getLevels();
</script>
You used the wrong way to find index in your code. If you used element index, it will avoid real index in your array and gives the wrong output. Check below code, it may be work for you requirement.
<input type="checkbox" value="degree">
<input type="checkbox" value="pgd">
<input type="checkbox" value="hnd">
<input type="checkbox" value="advdip">
<script src="https://code.jquery.com/jquery-3.5.0.min.js" integrity="sha256-xNzN2a4ltkB44Mc/Jz3pT4iU1cmeR0FkXs4pru/JxaQ=" crossorigin="anonymous"></script>
<script>
function getLevels() {
// get reference to container div of checkboxes
var con = document.getElementById('course-levels');
// get reference to input elements in course-levels container
var inp = document.getElementsByTagName('input');
// create array to hold checkbox values
var selectedValues = [];
// collect each input value on click
for (var i = 0; i < inp.length; i++) {
// if input is checkbox
if (inp[i].type === 'checkbox') {
// on each checkbox click
inp[i].onclick = function() {
if ($(this).prop("checked") == true) {
selectedValues.push(this.value);
console.log(selectedValues);
}
else if ($(this).prop("checked") == false) {
// get index number
var index = selectedValues.indexOf(this.value);
selectedValues.splice(index, 1);
console.log(selectedValues);
}
}
}
}
}
getLevels();
</script>
Add change handler to the inputs and use jQuery map to get the values of the checked inputs.
var levels
$('#checkArray input').on('change', function () {
levels = $('#checkArray input:checked').map(function () {
return this.value
}).get()
console.log(levels)
}).eq(0).change()
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<fieldset id="checkArray">
<input type="checkbox" value="degree" checked>
<input type="checkbox" value="pgd">
<input type="checkbox" value="hnd">
<input type="checkbox" value="advdip">
</fieldset>
my approach was to add an event handler that reads all checked values when any of those inputs is clicked and empty the array before loging the response. no need to add any dependencies with this one
Hope this is what you are looking for
function getLevels() {
let checkboxContainer = document.getElementById("checkboxContainer");
let inputs = checkboxContainer.querySelectorAll("input");
let checked = [];
inputs.forEach( (input) => {
checked = [];
input.addEventListener( 'click', () => {
checked = [];
inputs.forEach( (e) => {
e.checked ? checked.push(e.value) : null;
})
console.log(checked);
});
});
}
getLevels();
<div id="checkboxContainer">
<input type="checkbox" value="degree" >
<input type="checkbox" value="pgd">
<input type="checkbox" value="hnd">
<input type="checkbox" value="advdip">
</div>
I don't know if this is what you need, to show an array of the selected values, if you want you can call the function that calculates on the check.
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.0.0/jquery.min.js"></script>
<fieldset id="checkArray">
<input type="checkbox" value="degree" checked>
<input type="checkbox" value="pgd">
<input type="checkbox" value="hnd">
<input type="checkbox" value="advdip">
</fieldset>
<button onclick="getLevels()">getLevels</button>
<script>
function getLevels() {
var levels = [];
$.each($("input:checked"), function() {
levels.push(($(this).val()));
});
console.log(levels);
}
getLevels();
</script>

Javascript checkbox onChange

I have a checkbox in a form and I'd like it to work according to following scenario:
if someone checks it, the value of a textfield (totalCost) should be set to 10.
then, if I go back and uncheck it, a function calculate() sets the value of totalCost according to other parameters in the form.
So basically, I need the part where, when I check the checkbox I do one thing and when I uncheck it, I do another.
Pure javascript:
const checkbox = document.getElementById('myCheckbox')
checkbox.addEventListener('change', (event) => {
if (event.currentTarget.checked) {
alert('checked');
} else {
alert('not checked');
}
})
My Checkbox: <input id="myCheckbox" type="checkbox" />
function calc()
{
if (document.getElementById('xxx').checked)
{
document.getElementById('totalCost').value = 10;
} else {
calculate();
}
}
HTML
<input type="checkbox" id="xxx" name="xxx" onclick="calc();"/>
If you are using jQuery.. then I can suggest the following:
NOTE: I made some assumption here
$('#my_checkbox').click(function(){
if($(this).is(':checked')){
$('input[name="totalCost"]').val(10);
} else {
calculate();
}
});
Use an onclick event, because every click on a checkbox actually changes it.
The following solution makes use of jquery. Let's assume you have a checkbox with id of checkboxId.
const checkbox = $("#checkboxId");
checkbox.change(function(event) {
var checkbox = event.target;
if (checkbox.checked) {
//Checkbox has been checked
} else {
//Checkbox has been unchecked
}
});
HTML:
<input type="checkbox" onchange="handleChange(event)">
JS:
function handleChange(e) {
const {checked} = e.target;
}
Reference the checkbox by it's id and not with the #
Assign the function to the onclick attribute rather than using the change attribute
var checkbox = $("save_" + fieldName);
checkbox.onclick = function(event) {
var checkbox = event.target;
if (checkbox.checked) {
//Checkbox has been checked
} else {
//Checkbox has been unchecked
}
};
Javascript
// on toggle method
// to check status of checkbox
function onToggle() {
// check if checkbox is checked
if (document.querySelector('#my-checkbox').checked) {
// if checked
console.log('checked');
} else {
// if unchecked
console.log('unchecked');
}
}
HTML
<input id="my-checkbox" type="checkbox" onclick="onToggle()">
try
totalCost.value = checkbox.checked ? 10 : calculate();
function change(checkbox) {
totalCost.value = checkbox.checked ? 10 : calculate();
}
function calculate() {
return other.value*2;
}
input { display: block}
Checkbox: <input type="checkbox" onclick="change(this)"/>
Total cost: <input id="totalCost" type="number" value=5 />
Other: <input id="other" type="number" value=7 />
I know this seems like noob answer but I'm putting it here so that it can help others in the future.
Suppose you are building a table with a foreach loop. And at the same time adding checkboxes at the end.
<!-- Begin Loop-->
<tr>
<td><?=$criteria?></td>
<td><?=$indicator?></td>
<td><?=$target?></td>
<td>
<div class="form-check">
<input type="checkbox" class="form-check-input" name="active" value="<?=$id?>" <?=$status?'checked':''?>>
<!-- mark as 'checked' if checkbox was selected on a previous save -->
</div>
</td>
</tr>
<!-- End of Loop -->
You place a button below the table with a hidden input:
<form method="post" action="/goalobj-review" id="goalobj">
<!-- we retrieve saved checkboxes & concatenate them into a string separated by commas.i.e. $saved_data = "1,2,3"; -->
<input type="hidden" name="result" id="selected" value="<?= $saved_data ?>>
<button type="submit" class="btn btn-info" form="goalobj">Submit Changes</button>
</form>
You can write your script like so:
<script type="text/javascript">
var checkboxes = document.getElementsByClassName('form-check-input');
var i;
var tid = setInterval(function () {
if (document.readyState !== "complete") {
return;
}
clearInterval(tid);
for(i=0;i<checkboxes.length;i++){
checkboxes[i].addEventListener('click',checkBoxValue);
}
},100);
function checkBoxValue(event) {
var selected = document.querySelector("input[id=selected]");
var result = 0;
if(this.checked) {
if(selected.value.length > 0) {
result = selected.value + "," + this.value;
document.querySelector("input[id=selected]").value = result;
} else {
result = this.value;
document.querySelector("input[id=selected]").value = result;
}
}
if(! this.checked) {
// trigger if unchecked. if checkbox is marked as 'checked' from a previous saved is deselected, this will also remove its corresponding value from our hidden input.
var compact = selected.value.split(","); // split string into array
var index = compact.indexOf(this.value); // return index of our selected checkbox
compact.splice(index,1); // removes 1 item at specified index
var newValue = compact.join(",") // returns a new string
document.querySelector("input[id=selected]").value = newValue;
}
}
</script>
The ids of your checkboxes will be submitted as a string "1,2" within the result variable. You can then break it up at the controller level however you want.

Categories