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.
Related
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(' ');
}
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 am having dynamically created checkbox...
I want that checked value from the checkbox should be stored in one array...
I am Facing the following Problems...
*
var checkedvalue=document.querySelectorAll('input[type=checkbox]:checked');
If I alert the value of checkedvalue It given undefined
If I have console.log the final variable console.log(array); It given the
["on"] in the console.log if the value is checked.
I didn't get the actual value.My code is given below. I don't know what is the mistake I did. Anyone could you please help me.
Thanks in Advance
<input type="Submit" Value="add" onclick="searchinput()">
--------------
function searchinput()
{
var li=document.createElement("li");
//creating checkbox
var label=document.createElement('label');
label.className="lab_style";
li.appendChild(label);
var check=document.createElement('input');
check.type="checkbox";
check.name="check_bo";
li.appendChild(check);
check.addEventListener('click', function() {
var array=[];
var checkedvalue=document.querySelectorAll('input[type=checkbox]:checked');
alert(checkedvalue.value);
for (var i = 0; i < checkedvalue.length; i++) {
array.push(checkedvalue[i].value);
console.log(array);
}
}, false);
}
one of the problems you are facing is that
document.querySelectorAll('input[type=checkbox]:checked');
returns a NodeList and value is not a property on an NodeList object. That is why you are seeing "undefined" in your alert.
Changing as little of your code as possible, I think this should work:
function searchinput()
{
var li=document.createElement("li");
//creating checkbox
var label=document.createElement('label');
label.className="lab_style";
li.appendChild(label);
var check=document.createElement('input');
check.type="checkbox";
check.name="check_bo";
li.appendChild(check);
check.addEventListener('click', function() {
var array=[];
var checkedvalue = document.querySelectorAll('input[type=checkbox]:checked');
for (var i = 0; i < checkedvalue.length; i++) {
if(checkedvalue[i].checked) {
array.push(checkedvalue[i].value);
}
}
}, false);
}
If you have a form with a bunch of checkboxes and once the form is submitted you want to have the values of all the checkboxes which are checked stored in an array then you can do it like this.
const checkboxes = document.querySelectorAll("input[type=checkbox]");
const form = document.querySelector("form");
const arr = [];
form.addEventListener("submit", (e) => {
e.preventDefault()
checkboxes.forEach(chbox => {
if (chbox.checked) {
arr.push(chbox.value)
}
})
console.log(arr)
})
<form>
<label>Apple:
<input type="checkbox" value="apple" name="test"></label>
<label>Mango:
<input type="checkbox" value="mango" name="test"></label>
<label>Banana:
<input type="checkbox" value="banana" name="test"></label>
<label>Grape:
<input type="checkbox" value="grape" name="test"></label>
<button type="submit">Submit</button>
</form>
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>
my angular js function code
$scope.cardcall = function (cardtype) {
$scope.cityname=cityname;
$http({method: 'GET',url: '/api/v1/asasas&filterBy=cardNames&filterByValue='+cardtype.key}).success(function(data) {
$scope.deal = data.deals;
});
};
my view code
<div class="check_box" ng-repeat="cardtype in card.cardTypes.buckets">
<label>
<input type="checkbox" value=" {{cardtype.key}}" name="cardname" ng-click="cardcall(cardtype)" /> {{cardtype.key}}
</label>
</div>
now when some click on check box it call api like
/api/v1/asasas&filterBy=cardNames&filterByValue=asssas
What i am try to make when some one click 2nd check box then api call like
/api/v1/asasas&filterBy=cardNames&filterByValue=asssas,xsdza
You could add a .checked value to cardtype via ng-model
<input type="checkbox" ng-model="cardtype.checked" value=" {{cardtype.key}}" name="cardname" ng-change="typecall()" />
Then you could run a loop in your code to determine what's checked
$scope.cardcall = function () {
$scope.cityname=cityname;
var keys = [],
buckets = $scope.card.cardTypes.buckets;
for (var i = 0, len = buckets.length, i < len; i++) {
if (buckets[i].checked)
keys.push(buckets[i].key);
}
if (keys.length) {
keys = keys.join();
$http({method: 'GET',url: '/api/v1/asasas&filterBy=cardNames&filterByValue=' + keys}).success(function(data) {
$scope.deal = data.deals;
});
}
};
This will be called every time one of those checkboxes gets checked or unchecked and since it looks through all of the checkboxes there's no need to pass cardtype.key anymore. If no checkboxes are checked it won't do an AJAX call.