So I have these checkboxes:
<input type="checkbox" name="type" value="4" />
<input type="checkbox" name="type" value="3" />
<input type="checkbox" name="type" value="1" />
<input type="checkbox" name="type" value="5" />
And so on. There are about 6 of them and are hand-coded (i.e not fetched from a db) so they are likely to remain the same for a while.
My question is how I can get them all in an array (in javascript), so I can use them while making an AJAX $.post
request using Jquery.
Any thoughts?
Edit: I would only want the selected checkboxes to be added to the array
This question is related to
javascript
jquery
ajax
dhtml
If you want to use a vanilla JS, you can do it similarly to a @zahid-ullah, but avoiding a loop:
var values = [].filter.call(document.getElementsByName('fruits[]'), function(c) {
return c.checked;
}).map(function(c) {
return c.value;
});
The same code in ES6 looks a way better:
var values = [].filter.call(document.getElementsByName('fruits[]'), (c) => c.checked).map(c => c.value);
window.serialize = function serialize() {_x000D_
var values = [].filter.call(document.getElementsByName('fruits[]'), function(c) {_x000D_
return c.checked;_x000D_
}).map(function(c) {_x000D_
return c.value;_x000D_
});_x000D_
document.getElementById('serialized').innerText = JSON.stringify(values);_x000D_
}
_x000D_
label {_x000D_
display: block;_x000D_
}
_x000D_
<label>_x000D_
<input type="checkbox" name="fruits[]" value="banana">Banana_x000D_
</label>_x000D_
<label>_x000D_
<input type="checkbox" name="fruits[]" value="apple">Apple_x000D_
</label>_x000D_
<label>_x000D_
<input type="checkbox" name="fruits[]" value="peach">Peach_x000D_
</label>_x000D_
<label>_x000D_
<input type="checkbox" name="fruits[]" value="orange">Orange_x000D_
</label>_x000D_
<label>_x000D_
<input type="checkbox" name="fruits[]" value="strawberry">Strawberry_x000D_
</label>_x000D_
<button onclick="serialize()">Serialize_x000D_
</button>_x000D_
<div id="serialized">_x000D_
</div>
_x000D_
function selectedValues(ele){_x000D_
var arr = [];_x000D_
for(var i = 0; i < ele.length; i++){_x000D_
if(ele[i].type == 'checkbox' && ele[i].checked){_x000D_
arr.push(ele[i].value);_x000D_
}_x000D_
}_x000D_
return arr;_x000D_
}
_x000D_
This should do the trick:
$('input:checked');
I don't think you've got other elements that can be checked, but if you do, you'd have to make it more specific:
$('input:checkbox:checked');
$('input:checkbox').filter(':checked');
var checkedValues = $('input:checkbox.vdrSelected:checked').map(function () {
return this.value;
}).get();
Use commented if block to prevent add values which has already in array if you use button click or something to run the insertion
$('#myDiv').change(function() {_x000D_
var values = [];_x000D_
{_x000D_
$('#myDiv :checked').each(function() {_x000D_
//if(values.indexOf($(this).val()) === -1){_x000D_
values.push($(this).val());_x000D_
// }_x000D_
});_x000D_
console.log(values);_x000D_
}_x000D_
});
_x000D_
<div id="myDiv">_x000D_
<input type="checkbox" name="type" value="4" />_x000D_
<input type="checkbox" name="type" value="3" />_x000D_
<input type="checkbox" name="type" value="1" />_x000D_
<input type="checkbox" name="type" value="5" />_x000D_
</div>_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
_x000D_
In MooTools 1.3 (latest at the time of writing):
var array = [];
$$("input[type=checkbox]:checked").each(function(i){
array.push( i.value );
});
Pure JavaScript with no need for temporary variables:
Array.from(document.querySelectorAll("input[type=checkbox][name=type]:checked")).map(e => e.value)
here is my code for the same problem someone can also try this. jquery
<script>
$(document).ready(function(){`
$(".check11").change(function(){
var favorite1 = [];
$.each($("input[name='check1']:checked"), function(){
favorite1.push($(this).val());
document.getElementById("countch1").innerHTML=favorite1;
});
});
});
</script>
var array = []
$("input:checkbox[name=type]:checked").each(function(){
array.push($(this).val());
});
var chk_arr = document.getElementsByName("chkRights[]");
var chklength = chk_arr.length;
for(k=0;k< chklength;k++)
{
chk_arr[k].checked = false;
}
In Javascript it would be like this (Demo Link):
// get selected checkboxes
function getSelectedChbox(frm) {
var selchbox = [];// array that will store the value of selected checkboxes
// gets all the input tags in frm, and their number
var inpfields = frm.getElementsByTagName('input');
var nr_inpfields = inpfields.length;
// traverse the inpfields elements, and adds the value of selected (checked) checkbox in selchbox
for(var i=0; i<nr_inpfields; i++) {
if(inpfields[i].type == 'checkbox' && inpfields[i].checked == true) selchbox.push(inpfields[i].value);
}
return selchbox;
}
Using Jquery
You only need to add class to every input, i have add class "source" you can change it of course
<input class="source" type="checkbox" name="type" value="4" />
<input class="source" type="checkbox" name="type" value="3" />
<input class="source" type="checkbox" name="type" value="1" />
<input class="source" type="checkbox" name="type" value="5" />
<script type="text/javascript">
$(document).ready(function() {
var selected_value = []; // initialize empty array
$(".source:checked").each(function(){
selected_value.push($(this).val());
});
console.log(selected_value); //Press F12 to see all selected values
});
</script>
ES6 version:
const values = Array
.from(document.querySelectorAll('input[type="checkbox"]'))
.filter((checkbox) => checkbox.checked)
.map((checkbox) => checkbox.value);
function getCheckedValues() {_x000D_
return Array.from(document.querySelectorAll('input[type="checkbox"]'))_x000D_
.filter((checkbox) => checkbox.checked)_x000D_
.map((checkbox) => checkbox.value);_x000D_
}_x000D_
_x000D_
const resultEl = document.getElementById('result');_x000D_
_x000D_
document.getElementById('showResult').addEventListener('click', () => {_x000D_
resultEl.innerHTML = getCheckedValues();_x000D_
});
_x000D_
<input type="checkbox" name="type" value="1" />1_x000D_
<input type="checkbox" name="type" value="2" />2_x000D_
<input type="checkbox" name="type" value="3" />3_x000D_
<input type="checkbox" name="type" value="4" />4_x000D_
<input type="checkbox" name="type" value="5" />5_x000D_
_x000D_
<br><br>_x000D_
<button id="showResult">Show checked values</button>_x000D_
<br><br>_x000D_
<div id="result"></div>
_x000D_
Pure JS
For those who don't want to use jQuery
var array = []
var checkboxes = document.querySelectorAll('input[type=checkbox]:checked')
for (var i = 0; i < checkboxes.length; i++) {
array.push(checkboxes[i].value)
}
I didnt test it but it should work
<script type="text/javascript">
var selected = new Array();
$(document).ready(function() {
$("input:checkbox[name=type]:checked").each(function() {
selected.push($(this).val());
});
});
</script>
You could try something like this:
$('input[type="checkbox"]').change(function(){
var checkedValue = $('input:checkbox:checked').map(function(){
return this.value;
}).get();
alert(checkedValue); //display selected checkbox value
})
Here
$('input[type="checkbox"]').change(function() call when any checkbox checked or unchecked, after this
$('input:checkbox:checked').map(function() looping on all checkbox,
On checking add the value for checkbox and on dechecking subtract the value
$('#myDiv').change(function() {_x000D_
var values = 0.00;_x000D_
{_x000D_
$('#myDiv :checked').each(function() {_x000D_
//if(values.indexOf($(this).val()) === -1){_x000D_
values=values+parseFloat(($(this).val()));_x000D_
// }_x000D_
});_x000D_
console.log( parseFloat(values));_x000D_
}_x000D_
});
_x000D_
<div id="myDiv">_x000D_
<input type="checkbox" name="type" value="4.00" />_x000D_
<input type="checkbox" name="type" value="3.75" />_x000D_
<input type="checkbox" name="type" value="1.25" />_x000D_
<input type="checkbox" name="type" value="5.50" />_x000D_
</div>_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
_x000D_
Use this:
var arr = $('input:checkbox:checked').map(function () {
return this.value;
}).get();
Another way of doing this with vanilla JS in modern browsers (no IE support, and sadly no iOS Safari support at the time of writing) is with FormData.getAll():
var formdata = new FormData(document.getElementById("myform"));
var allchecked = formdata.getAll("type"); // "type" is the input name in the question
// allchecked is ["1","3","4","5"] -- if indeed all are checked
Source: Stackoverflow.com