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(' ');
}
Related
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
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>
I want the checked checkboxes to be unchecked when clicking another button:
Below is the HTML
<input type="checkbox" name="checkb" id="Agent" value="Agent"> type=Agent
<br />
<input type="checkbox" name="checkb" id="Customer" value="Customer"> type=Customer
<br />
<input type="checkbox" name="checkb" id="Phone" value="Phone"> type=Phone
<br />
<input type="checkbox" name="checkb" id="ID_Card" value="ID_Card"> type=ID_Card
<br />
<input type=datetime id="Start_Date" value="" placeholder="Start_Date" />
<input type=datetime id="End_Date" value="" placeholder="End_Date" />
<button id="date">
Interval
</button>
On clicking of the Interval button if any checkboxes are checked they should get unchecked.
Below is the event listener for the Interval button:
var check1 = document.getElementById("Agent");
var check2 = document.getElementById("Customer");
var check3 = document.getElementById("Phone");
var check4 = document.getElementById("ID_Card");
var newBtn = document.getElementById("date");
if (newBtn) {
newBtn.addEventListener("click", function() {
if (check1.checked) {
var ischecked1 = check1.checked;
check1.checked != ischecked1;
}
if (check2.checked) {
var ischecked2 = check2.checked;
check2.checked != ischecked2;
}
if (check3.checked) {
var ischecked3 = check3.checked;
check3.checked != ischecked3;
}
if (check4.checked) {
var ischecked4 = check4.checked;
check4.checked != ischecked4;
}
});
}
Below code runs without any errors, but the boxes do not get unchecked if they are checked.
Below is the fiddle
Your statements are just evaluating as booleans, not performing assignments:
check1.checked != ischecked1; // this returns a boolean, doesn't do any assignment
You want to do this to toggle the checked state:
check1.checked = !ischecked1;
Same thing for other checkboxes.
There's also no need to create the extra variables, you can just do the toggling and reading directly:
check1.checked = !check1.checked;
Since you're only toggling checkboxes when they are checked, you can just directly set them to false as well.
if (check1.checked) check1.checked = false;
Instead of having if statements, you can use array iteration to do the toggling:
[check1, check2, check3, check4].forEach(check => {
if (check.checked) {
check.checked = false;
}
});
// or query the checkboxes directly and do the same
[...document.querySelectorAll('input[type="checkbox"]')].forEach(check => {
if (check.checked) {
check.checked = false;
}
});
Your mistake is in this line:
check1.checked != ischecked1;
This actually means "compare if check1.checked is not equal to ischecked1".
Most simple solution would be to remove the if statement and just do this:
check1.checked = !check1.checked
This means "set check1.checked to the opposite of check1.checked".
Since all checkboxes have the same name you could also collect all checkboxes by requesting them by name and use a loop to walk through them. A small example:
// Collect all checkboxes with a CSS selector that matches all input
// elements with a name attribute that's equal to "checkb"
var checkboxes = document.querySelectorAll('input[name="checkb"]');
var newBtn = document.getElementById("date");
if (newBtn) {
newBtn.addEventListener("click", function() {
// this is a for loop, it will run for as long as i
// is smaller than the amount of found checkboxes (checkboxes.length)
for(var i = 0; i < checkboxes.length; i++) {
// Get the checkbox from the checkboxes collection
// collection[i] means get item from collection with index i
var checkbox = checkboxes[i];
// Revert the .checked property of the checkbox
checkbox.checked = !checkbox.checked;
}
});
}
By the looks of it you just want to uncheck everything on click of button
you can just do this
var newBtn = document.getElementById("date");
if (newBtn) {
newBtn.addEventListener("click", function() {
document.getElementById("Agent").checked =
document.getElementById("Customer").checked =
document.getElementById("Phone").checked =
document.getElementById("ID_Card").checked = false;
});
}
I have a group of 4 checkboxes.
When any two have been checked they have their values copied to two hidden input fields.
The first checked checkbox value goes to the first input id="checkedBox1"
How do I get the second checked checkbox value to go to the second hidden input field id="checkedBox2"
I have used the JavaScript function below to place the values into each input from the individual checkboxes but can't figure out how to iterate through the list of all four checkboxes and place the two checked ones into each separate input field.
Checkboxes:
<input type="checkbox" value="test1" id="a" name="one"><label>Test11</label>
<input type="checkbox" value="test2" id="b" name="one"><label>Test12</label>
<input type="checkbox" value="test3" id="c" name="one"><label>Test13</label>
<input type="checkbox" value="test4" id="d" name="one"><label>Test14</label>
<input type="hidden" value="" id="checkedBox1">
<input type="hidden" value="" id="checkedBox2">
<script>
function populate() {
var checkboxes = document.getElementsByName('one');
var ip1 = document.getElementById('checkedBox1');
var ip2 = document.getElementById('checkedBox2');
// clear current values
ip1.value = ip2.value = '';
var first = false;
var second = false;
// Loop over checkboxes,stop when found 2 that are checked
for (var i=0,iLen=checkboxes.length; i<iLen || !(first && second); i++) {
if (checkboxes[i].checked) {
if (!first) {
ip1.value = checkboxes[i].value;
first = true;
} else if (!second) {
ip2.value = checkboxes[i].value;
second = true;
}
}
}
}
$('input[type="checkbox"]').on('change', function() {
populate();
}).change();
</script>
You could try plain JS, though I would use form property access rather than getElementsByName or getElementById:
function populate() {
var checkboxes = document.getElementsByName('one');
var ip1 = document.getElementById('checkedBox1');
var ip2 = document.getElementById('checkedBox2');
// clear current values
ip1.value = ip2.value = '';
var first = false;
var second = false;
// Loop over checkboxes,stop when found 2 that are checked
for (var i=0,iLen=checkboxes.length; i<iLen || !(first && second); i++) {
if (checkboxes[i].checked) {
if (!first) {
ip1.value = checkboxes[i].value;
first = true;
} else if (!second) {
ip2.value = checkboxes[i].value;
second = true;
}
}
}
}
Edit
Thanks Mal, added a line to clear the values of the hidden inputs each time.
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.