I'm trying to build system that will recognize when new checkbox is checked, once the checkbox is checked, the user will have to choose one of the options: left, right, all.
Once one of the three is chosen, the checked checkboxes will be pushed into their specific array. (all[], right[], left[])
The problem:
Lets assume I check checkbox number 1, and click all.
Debugging:
all["1"]
then I check checkbox number 3, and click left.
I will get the following debugging:
Debugging:
all["1"]
left["1", "3"]
Desired result:
all["1"]
left["3"]
I want left[] array to get only the new checkbox checking, but without unchecking the checkboxes.
Codepen
$(document).ready(function () {
//Adding each checked checkbox to array
let checked = [], all = [], left = [], right = [];
$box = $('.ppom-check-input');
$box.on('change', function() {
checked = $box.filter(':checked').map((i,c) => c.value).get();
$('#choose').addClass('active');
console.log( checked );
});
//Push the value to array
$('.all,.left,.right').on('click', function() {
if( $(this).is('.all') ) {
all = [...new Set( all.concat(checked) )];
$('#choose').removeClass('active');
} else if( $(this).is('.left') ) {
left = [...new Set( left.concat(checked) )];
$('#choose').removeClass('active');
} else if( $(this).is('.right') ){
right = [...new Set( right.concat(checked) )];
$('#choose').removeClass('active');
}
console.log( 'all',all, 'left', left, 'right', right );
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="checkbox" value="1" class="ppom-check-input" />
1
<br/>
<input type="checkbox" value="2" class="ppom-check-input" />
2
<br/>
<input type="checkbox" value="3" class="ppom-check-input" />
3
<br/>
<input type="checkbox" value="4" class="ppom-check-input" />
4
<br/>
<input type="checkbox" value="5" class="ppom-check-input" />
5
<br/>
<div id="choose">
left
right
all
</div>
How can I push to an array new values only (not all checked checkboxes)?
One way to do above is giving some class to checkboxes whenever its checked using addClass("selected_new") then remove same only when any of a tag is clicked then only checkboxes which is newly selected will be added in array.
Demo Code :
$(document).ready(function() {
//Adding each checked checkbox to array
let checked = [],
all = [],
left = [],
right = [];
$box = $('.ppom-check-input');
$box.on('change', function() {
//if checked then only
if ($(this).is(":checked")) {
//added new class
$(this).addClass("selected_new")
//or
//$(this).attr("data-selected", "selected_new")
}
//or [data-selected=selected_new]:checked
checked = $box.filter('.selected_new:checked').map((i, c) => c.value).get();
$('#choose').addClass('active');
});
$('.all,.left,.right').on('click', function() {
console.clear()
//remove class once any link is clicked
$("input[type=checkbox]").removeClass("selected_new")
//or
//$("input[type=checkbox]").attr("data-selected", "")
if ($(this).is('.all')) {
all = [...new Set(all.concat(checked))];
$('#choose').removeClass('active');
} else if ($(this).is('.left')) {
left = [...new Set(left.concat(checked))];
$('#choose').removeClass('active');
} else if ($(this).is('.right')) {
right = [...new Set(right.concat(checked))];
$('#choose').removeClass('active');
}
console.log('all', all, 'left', left, 'right', right);
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="checkbox" value="1" class="ppom-check-input" /> 1
<br/>
<input type="checkbox" value="2" class="ppom-check-input" /> 2
<br/>
<input type="checkbox" value="3" class="ppom-check-input" /> 3
<br/>
<input type="checkbox" value="4" class="ppom-check-input" /> 4
<br/>
<input type="checkbox" value="5" class="ppom-check-input" /> 5
<br/>
<div id="choose">
left
right
all
</div>
Related
I have a list of the checkbox when clicking on any checkbox than new array append (push) in the main array. If uncheck than remove but not change any index for the current array.
explain:-
Like:- When I click on the first checkbox than array like
0: ["2"]
Like:- When I click on the second checkbox than array like
0: ["2"]
1: ["3"]
Like :- When I click on four checkbox than array like
0: ["2"]
1: ["3"]
2: ["5"]
after than uncheck checkbox if I uncheck first tthe han I needed array
1: ["3"]
2: ["5"]
again I click on first checkbox than need array link
1: ["3"]
2: ["5"]
3: ["2"]
Not need to change any array index key
https://jsfiddle.net/tx63yjhg/
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="checkbox" value="1" />
<input type="checkbox" value="2" />
<input type="checkbox" value="3" />
<input type="checkbox" value="4" />
<input type="checkbox" value="5" />
<input type="checkbox" value="6" />
<input type="checkbox" value="7" />
<script type="text/javascript">
var values = [];
var new_value = [];
$("input").on("change", function()
{
var $this = $(this);
if ($this.is(":checked"))
{
var new_data = [$this.val()];
new_value.push(new_data);
}
else
{
//remove array when uncheck checkbox
}
console.log('new_value',new_value);
});
</script>
How I can remove array and add again??
I am not sure whether you achieve the same using an array of arrays or not. You can instead try use an object like following.
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="checkbox" value="1" />
<input type="checkbox" value="2" />
<input type="checkbox" value="3" />
<input type="checkbox" value="4" />
<input type="checkbox" value="5" />
<input type="checkbox" value="6" />
<input type="checkbox" value="7" />
<script type="text/javascript">
var values = [];
var new_value = {};
var counter = 0;
$("input").on("change", function() {
var $this = $(this);
if ($this.is(":checked")) {
new_value[counter++] = [$this.val()];
} else {
Object.entries(new_value).forEach(([k,v]) => {
if(v.includes($this.val())) delete new_value[k];
});
}
console.log('new_value',new_value);
});
</script>
EDIT
For add
new_value[counter++] = {id1: 100, id2: 200, "id3": 300,"value":474}; // e.g. object
For remove
let valueToBeRemoved = 234; // e.g. value to be removed
Object.entries(new_value).forEach(([k,v]) => {
if(v.value === valueToBeRemoved) delete new_value[k];
})
EDIT 2
for (var k in new_value) {
if(new_value[k].value === valueToBeRemoved) delete new_value[k];
}
It easy:
var values = [];
$("input").on("change", function()
{
var $this = $(this);
var new_value = [];
if ($this.is(":checked"))
{
var new_data = [$this.val()];
new_value.push(new_data);
}
console.log('new_value',new_value);
});
I am displaying some check boxes. The user can check a maximum of 4 boxes. I store the checked value in 4 textboxes.
My problem: How can I correctly store the "new" checked value when the user randomly unchecks one box and checks another?
I store values as follows: First checked into item_1, second checked into item_2, third checked into item_3 ... If the user unchecks the first checked box, for example, how can I store the value of the next box he or she checks into item_1? Please help.
Simplified code
<input type="checkbox" name="prodname_1" id="prodname_1"value="1"/>
<input type="checkbox" name="prodname_2" id="prodname_2"value="2"/>
<input type="checkbox" name="prodname_3" id="prodname_3"value="3"/>
.
.
<input type="checkbox" name="prodname_10" id="prodname_10"value="10"/>
<input type="text" name="item_0" id="item_0"value=""/>
<input type="text" name="item_1" id="item_1"value=""/>
<input type="text" name="item_2" id="item_2"value=""/>
<input type="text" name="item_3" id="item_3"value=""/>
$(document).ready(function (e)
{
counter=0;
$('input[id^="prodname_"]').change(function()
{
id = $(this).attr('id');
var arr = id.split('_');
valueChecked=$('#'+id).val();
if(this.checked)
{
if(counter==4)
{
alert('Allready checked 4 items');
this.checked=false;
return false;
}
$("#item_"+counter).val(valueChecked);
++counter;
}
});
});
Instead of retaining a counter, just count the number of checked boxes when the change occurs.
Revised to use the logic you intended (took a little while to figure that out) :)
JSFiddle: http://jsfiddle.net/TrueBlueAussie/tmLnbvv0/9/
$(document).ready(function (e) {
var $items = $('input[id^="item_"]');
var checkboxes = $('input[id ^= "prodname_"]').change(function () {
var id = $(this).attr('id');
var arr = id.split('_');
valueChecked = $(this).val();
// Count of checked checkboxes
var counter = checkboxes.filter(':checked').length;
if ($(this).is(':checked')) {
// count the checked checkboxes
if (counter > 4) {
alert('Already checked 4 items');
$(this).prop('checked', false);
} else {
// Add to the first available slot
$items.filter(function(){return $(this).val() == ""}).first().val(valueChecked);
}
} else {
// Remove the matching value
$items.filter(function(){return $(this).val() == valueChecked;}).first().val('');
}
});
});
note: The "jQuery way" for changing checkboxes is to use prop('checked', booleanvalue) (also changed above)
V2 - If you don't want gaps:
This version is actually simpler as it just clears the items and fills them, in order, with any checked checkbox values.
JSFiddle: http://jsfiddle.net/TrueBlueAussie/tmLnbvv0/13/
$(document).ready(function (e) {
var $items = $('input[id^="item_"]');
var $checkboxes = $('input[id ^= "prodname_"]').change(function () {
// Count of checked checkboxes
var counter = $checkboxes.filter(':checked').length;
// count the checked checkboxes
if (counter > 4) {
alert('Already checked 4 items');
$(this).prop('checked', false);
}
// Clear all the items
$items.val('');
// Fill the items with the selected values
var item = 0;
$checkboxes.filter(':checked').each(function () {
$('#item_' + (item++)).val($(this).val());
});
});
});
Look at
$(document).ready(function(e) {
var counter = 0,
$items = $('input[name^="item_"]');
$('input[id^="prodname_"]').change(function() {
var id = this;
if (this.checked) {
if (counter == 4) {
this.checked = false;
return;
}
$("#item_" + counter).val(this.value).attr('data-value', this.value);
++counter;
} else {
var $item = $items.filter('[data-value="' + this.value + '"]');
var index = $items.index($item);
$items.slice(index, counter).each(function(i) {
var $n = $items.eq(index + i + 1);
$(this).val($n.val() || '').attr('data-value', $n.attr('data-value'));
});
counter--;
$("#item_" + counter).val('').removeAttr('data-value');
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<input type="checkbox" name="prodname_1" id="prodname_1" value="1" />
<input type="checkbox" name="prodname_2" id="prodname_2" value="2" />
<input type="checkbox" name="prodname_3" id="prodname_3" value="3" />
<input type="checkbox" name="prodname_4" id="prodname_4" value="4" />
<input type="checkbox" name="prodname_5" id="prodname_5" value="5" />
<input type="checkbox" name="prodname_6" id="prodname_6" value="6" />
<input type="checkbox" name="prodname_7" id="prodname_7" value="7" />
<input type="checkbox" name="prodname_8" id="prodname_8" value="8" />
<input type="checkbox" name="prodname_9" id="prodname_9" value="9" />
<input type="checkbox" name="prodname_10" id="prodname_10" value="10" />
<input type="text" name="item_0" id="item_0" value="" />
<input type="text" name="item_1" id="item_1" value="" />
<input type="text" name="item_2" id="item_2" value="" />
<input type="text" name="item_3" id="item_3" value="" />
I have many server input checkboxes. I have given the first checkbox the id all. By default it will be checked. When the user checks other checkboxes, then checkbox with id all will be unchecked. And if all is checked other checkboxes will be unchecked. For this to happen i made the code but nothing is happening.
Here is what i have tried.
<form>
<input type="checkbox" id="all" value="all" name="all" onChange="check()" checked/>ALL <br/>
<input type="checkbox" id="servers" value="xampp" name="server[]" onChange="check()" />XAMPP <br/>
<input type="checkbox" id="servers" value="wamp" name="server[]" onChange="check()" />WAMP <br/>
<input type="checkbox" id="servers" value="mamp" name="server[]" onChange="check()" />MAMP <br/>
<input type="checkbox" id="servers" value="amp" name="server[]" onChange="check()" />AMP <br/>
</form>
function check(){
var all = document.getElementById("all"),
group = document.getElementById("servers");
if(all.checked == true){
group.checked == false;
}elseif(group.checked == true){
all.checked == false;
}
}
I wanted my code to work like THIS.
I dont want to use jQuery for some reasons. So i need my code to be in pure JS.
Any help will be appreciated.
You can't use the same ID on multiple elements.
Try this, notice how I placed the checkboxes in a div
Here it is working: http://jsfiddle.net/Sa2d3/
HTML:
<form>
<div id="checkboxes">
<input type="checkbox" id="all" value="all" name="all" onChange="check()" />ALL <br/>
<input type="checkbox" value="xampp" name="server[]" onChange="check()" />XAMPP <br/>
<input type="checkbox" value="wamp" name="server[]" onChange="check()" />WAMP <br/>
<input type="checkbox" value="mamp" name="server[]" onChange="check()" />MAMP <br/>
<input type="checkbox" value="amp" name="server[]" onChange="check()" />AMP <br/>
</div>
</form>
JavaScript:
document.getElementById('checkboxes').addEventListener('change', function(e) {
var el = e.target;
var inputs = document.getElementById('checkboxes').getElementsByTagName('input');
// If 'all' was clicked
if (el.id === 'all') {
// loop through all the inputs, skipping the first one
for (var i = 1, input; input = inputs[i++]; ) {
// Set each input's value to 'all'.
input.checked = el.checked;
}
}
// We need to check if all checkboxes have been checked
else {
var numChecked = 0;
for (var i = 1, input; input = inputs[i++]; ) {
if (input.checked) {
numChecked++;
}
}
// If all checkboxes have been checked, then check 'all' as well
inputs[0].checked = numChecked === inputs.length - 1;
}
}, false);
EDIT:
Based on your request in the comment here is the updated javascript:
http://jsfiddle.net/T5Pm7/
document.getElementById('checkboxes').addEventListener('change', function(e) {
var el = e.target;
var inputs = document.getElementById('checkboxes').getElementsByTagName('input');
// If 'all' was clicked
if (el.id === 'all') {
// If 'all' is checked
if (el.checked) {
// Loop through the other inputs and removed the check
for (var i = 1, input; input = inputs[i++]; ) {
input.checked = false;
}
}
}
// If another has been clicked, remove the check from 'all'
else {
inputs[0].checked = false;
}
}, false);
You can only assign the same id to one element. What you want to do is give them a class="servers" and then use document.getElementsByClassName("servers"); in your JavaScript.
You cannot have same id for multiple HTML elements. You could do something like this to achieve what you are asking for.
<form>
<input type="checkbox" id="all" value="all" name="all" onChange="check(this, 'a')" checked/>ALL <br/>
<input type="checkbox" id="servers1" value="xampp" name="server[]" onChange="check(this, 's')" />XAMPP <br/>
<input type="checkbox" id="servers2" value="wamp" name="server[]" onChange="check(this, 's')" />WAMP <br/>
<input type="checkbox" id="servers3" value="mamp" name="server[]" onChange="check(this, 's')" />MAMP <br/>
<input type="checkbox" id="servers4" value="amp" name="server[]" onChange="check(this, 's')" />AMP <br/>
</form>
<script>
function check(cb, type){
var all = document.getElementById("all");
if (type == "a" && cb.checked){
var els = document.getElementsByName("server[]");
for(var i = 0; i < els.length; ++i)
els[i].checked = false;
} else if( type == "s" && cb.checked) {
all.checked = false;
}
}
</script>
put this function
function jvcheck(id,Vale){
Checkboxesclass = '.group'+id;
$(Checkboxesclass).each(function() {
this.checked = Vale;
});
}
and then put this code in your main checkbox
jvcheck('group222',this.checked);
all checkbox with class group222 now checked .
How would I go about detecting the order in which checkboxes are checked? I have a list of checkboxes on a form, and I need to have users select their first and second choices (but no more). So, given this:
<input name="checkbox1" type="checkbox" value="a1"> Option 1
<input name="checkbox1" type="checkbox" value="a2"> Option 2
<input name="checkbox1" type="checkbox" value="a3"> Option 3
<input name="checkbox1" type="checkbox" value="a4"> Option 4
If someone selects option 2, then option 3, I'd like to have some indicator that option 2 was the first choice, and option 3 was the second choice. Any ideas?
Thanks in advance.
Update:
These are extremely helpful suggestions, thank you. As I test these examples, it's giving me a better idea of how to approach the problem - but I'm still a bit stuck (I'm a JS novice). What I want to do is have these labels change as the checkboxes are checked or unchecked, to indicate which is the first or second selection:
<label id="lblA1"></label><input name="checkbox1" type="checkbox" value="a1"> Option 1
<label id="lblA2"></label><input name="checkbox1" type="checkbox" value="a2"> Option 2
<label id="lblA3"></label><input name="checkbox1" type="checkbox" value="a3"> Option 3
<label id="lblA4"></label><input name="checkbox1" type="checkbox" value="a4"> Option 4
So if someone clicks Option 2, then Option 3, lblA2 will display "First", and lblA3 will display "Second". If someone unchecks Option 2 while Option 3 is still checked, lblA3 becomes "First". Hopefully this makes sense?
Thanks!
If you are using jQuery. Below code is does what you have explained and it is tested.
I have used global variables.
<input name="checkbox1" type="checkbox" value="a1" /> Option 1
<input name="checkbox1" type="checkbox" value="a2" /> Option 2
<input name="checkbox1" type="checkbox" value="a3" /> Option 3
<input name="checkbox1" type="checkbox" value="a4" /> Option 4
<input type="button" value="do" id="btn" />
As shown below, it also handles the situation that user unchecks a choice.
$(document).ready(function () {
var first = "";
var second = "";
$('input[name="checkbox1"]').change(function () {
if ($(this).attr('checked')) {
if (first == "") {
first = $(this).attr('value');
}
else if (second == "") {
second = $(this).attr('value');
}
}
else {
if (second == $(this).attr('value')) {
second = "";
}
else if (first == $(this).attr('value')) {
first = second;
second = "";
}
}
});
$('#btn').click(function () {
alert(first);
alert(second);
});
});
I hope that it will be helpful.
UPDATE [IMPORTANT]:
I have noticed that my previous code was incomplete, for example, if you check a1, then a2, then a3, then uncheck a2; my code was not recognising a3 as second.
Here is the complete solution of your updated problem. I used array this time.
The complete HTML:
<label id="lblA1"></label>
<input name="checkbox1" type="checkbox" value="a1" /> Option 1
<label id="lblA2"></label>
<input name="checkbox1" type="checkbox" value="a2" /> Option 2
<label id="lblA3"></label>
<input name="checkbox1" type="checkbox" value="a3" /> Option 3
<label id="lblA4"></label>
<input name="checkbox1" type="checkbox" value="a4" /> Option 4
The complete Javascript:
$(document).ready(function () {
var array = [];
$('input[name="checkbox1"]').click(function () {
if ($(this).attr('checked')) {
// Add the new element if checked:
array.push($(this).attr('value'));
}
else {
// Remove the element if unchecked:
for (var i = 0; i < array.length; i++) {
if (array[i] == $(this).attr('value')) {
array.splice(i, 1);
}
}
}
// Clear all labels:
$("label").each(function (i, elem) {
$(elem).html("");
});
// Check the array and update labels.
for (var i = 0; i < array.length; i++) {
if (i == 0) {
$("#lbl" + array[i].toUpperCase()).html("first");
}
if (i == 1) {
$("#lbl" + array[i].toUpperCase()).html("second");
}
}
});
});
have 2 javascript variables first and second. whenever a checkbox is checked check if first is null if so assign the checkbox id to it, if first is not null set second.
You could have a change listener and a hidden field. Every time the user selects a checkbox, you add the value. Like so (assuming #parent is the parent element of the boxes):
$('#parent').delegate('input[type=checkbox]', 'change', function() {
if($(this).is(':checked')) {
$('#hidden').val($('#hidden').val() + " " + $(this).val())
}
});
The value of the hidden field would then be something like a2 a3 a1...
This is if you want to process the information at the server side. You can then split the string at the server side and examine it. Of course you have to handle removal and adding of selections.
If you just want to process the values on the client, you can add it to an array:
var selected = [];
$('#parent').delegate('input[type=checkbox]', 'change', function() {
if($(this).is(':checked')) {
selected.push($(this).val());
}
});
Try -
$(document).ready(function(){
var checked_no = 0;
$('input[name="checkbox1"]').change(function(){
alert($('input[name="checkbox1"]').filter(':checked').length);
checked_no = $('input[name="checkbox1"]').filter(':checked').length;
// checked_no acts as a counter for no of checkboxes checked.
});
});
Here you have it, if you want something more sophisticated (e.g. to test when an option is unclicked) you have to do some extra work. Just test this html in your browser:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<script type = "text/javascript">
var checkboxClicks = new Array(2);
function updateClickOrder(checkbox) {
if (checkbox.checked) {
if (checkboxClicks[0] ==null) {
checkboxClicks[0] = checkbox.value;
} else if (checkboxClicks[1] ==null) {
checkboxClicks[1] = checkbox.value;
}
}
document.forms[0].clickOrder.value = checkboxClicks[0] + ", " + checkboxClicks[1];
alert(document.forms[0].clickOrder.value);
//alert("Clicked " + checkbox.value);
}
</script>
</head>
<body>
<form name="testCheckboxClickOrder">
<input name="checkbox1" type="checkbox" value="a1" onchange="updateClickOrder(this);"> Option 1
<input name="checkbox1" type="checkbox" value="a2" onchange="updateClickOrder(this);"> Option 2
<input name="checkbox1" type="checkbox" value="a3" onchange="updateClickOrder(this);"> Option 3
<input name="checkbox1" type="checkbox" value="a4" onchange="updateClickOrder(this);"> Option 4
<input type="hidden" name="clickOrder"/>
</form>
</body>
</html>
This is going to save the order in an array. If you deselect the position is removed. The script will attempt to find the element by its value and remove. If you select again the value is added.
<input type="checkbox" value="v1" />
<input type="checkbox" value="v2" />
<input type="checkbox" value="v3" />
<input type="checkbox" value="v4" />
<textarea id="result"></textarea>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<script>
var userInput = [];
var c = 0;
$("input[type=checkbox]").click(function()
{
if ($(this).attr("checked"))
{
userInput[c] = $(this).val();
++c;
}
else
{
var i = parseInt(userInput.join().indexOf($(this).val())) - 2;
userInput.splice(i, 1);
}
});
$("textarea").click(function()
{
$(this).val("");
for (var i in userInput)
{
$(this).val($(this).val() + " " + userInput[i]);
}
});
</script>
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
</head>
<body>
<input name="checkbox1" type="checkbox" id="myCheck" value=" Option 1" onclick="myFunction('Option 1')" /> Option 1
<input name="checkbox1" type="checkbox" id="myCheck2" value=" Option 2" onclick="myFunction2('Option 2')" /> Option 2
<input name="checkbox1" type="checkbox" id="myCheck3" value=" Option 3" onclick="myFunction3('Option 3')" /> Option 3
<input name="checkbox1" type="checkbox" id="myCheck4" value=" Option 4" onclick="myFunction4('Option 4')" /> Option 4
<p id="getValues"></p>
</body>
<script>
var array = [];
function removeA(arr) {
var what, a = arguments, L = a.length, ax;
while (L > 1 && arr.length) {
what = a[--L];
while ((ax= arr.indexOf(what)) !== -1) {
arr.splice(ax, 1);
}
}
return arr;
}
function myFunction(text) {
// Get the checkbox
var checkBox = document.getElementById("myCheck");
// Get the output text
// If the checkbox is checked, display the output text
if (checkBox.checked == true)
{
array.push(text);
}
else
{
removeA(array, text);
}
getValues();
}
function myFunction2(text) {
// Get the checkbox
var checkBox = document.getElementById("myCheck2");
// Get the output text
// If the checkbox is checked, display the output text
if (checkBox.checked == true)
{
array.push(text);
}
else
{
removeA(array, text);
}
getValues();
}
function myFunction3(text) {
// Get the checkbox
var checkBox = document.getElementById("myCheck3");
// Get the output text
// If the checkbox is checked, display the output text
if (checkBox.checked == true)
{
array.push(text);
}
else
{
removeA(array, text);
}
getValues();
}
function myFunction4(text) {
// Get the checkbox
var checkBox = document.getElementById("myCheck4");
// Get the output text
// If the checkbox is checked, display the output text
if (checkBox.checked == true)
{
array.push(text);
}
else
{
removeA(array, text);
}
getValues();
}
function getValues()
{
$("#getValues").html(array.join("<br>"));
}
</script>
</html>
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
Formatted :
$("input:checkbox[name=type]:checked").each(function(){
yourArray.push($(this).val());
});
Hopefully, it will work.
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)
}
var chk_arr = document.getElementsByName("chkRights[]");
var chklength = chk_arr.length;
for(k=0;k< chklength;k++)
{
chk_arr[k].checked = false;
}
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>
Pure JavaScript with no need for temporary variables:
Array.from(document.querySelectorAll("input[type=checkbox][name=type]:checked"), e => e.value);
ES6 version:
const values = Array
.from(document.querySelectorAll('input[type="checkbox"]'))
.filter((checkbox) => checkbox.checked)
.map((checkbox) => checkbox.value);
function getCheckedValues() {
return Array.from(document.querySelectorAll('input[type="checkbox"]'))
.filter((checkbox) => checkbox.checked)
.map((checkbox) => checkbox.value);
}
const resultEl = document.getElementById('result');
document.getElementById('showResult').addEventListener('click', () => {
resultEl.innerHTML = getCheckedValues();
});
<input type="checkbox" name="type" value="1" />1
<input type="checkbox" name="type" value="2" />2
<input type="checkbox" name="type" value="3" />3
<input type="checkbox" name="type" value="4" />4
<input type="checkbox" name="type" value="5" />5
<br><br>
<button id="showResult">Show checked values</button>
<br><br>
<div id="result"></div>
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');
In MooTools 1.3 (latest at the time of writing):
var array = [];
$$("input[type=checkbox]:checked").each(function(i){
array.push( i.value );
});
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() {
var values = [].filter.call(document.getElementsByName('fruits[]'), function(c) {
return c.checked;
}).map(function(c) {
return c.value;
});
document.getElementById('serialized').innerText = JSON.stringify(values);
}
label {
display: block;
}
<label>
<input type="checkbox" name="fruits[]" value="banana">Banana
</label>
<label>
<input type="checkbox" name="fruits[]" value="apple">Apple
</label>
<label>
<input type="checkbox" name="fruits[]" value="peach">Peach
</label>
<label>
<input type="checkbox" name="fruits[]" value="orange">Orange
</label>
<label>
<input type="checkbox" name="fruits[]" value="strawberry">Strawberry
</label>
<button onclick="serialize()">Serialize
</button>
<div id="serialized">
</div>
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;
}
var checkedValues = $('input:checkbox.vdrSelected: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
Use this:
var arr = $('input:checkbox:checked').map(function () {
return this.value;
}).get();
On checking add the value for checkbox and on dechecking subtract the value
$('#myDiv').change(function() {
var values = 0.00;
{
$('#myDiv :checked').each(function() {
//if(values.indexOf($(this).val()) === -1){
values=values+parseFloat(($(this).val()));
// }
});
console.log( parseFloat(values));
}
});
<div id="myDiv">
<input type="checkbox" name="type" value="4.00" />
<input type="checkbox" name="type" value="3.75" />
<input type="checkbox" name="type" value="1.25" />
<input type="checkbox" name="type" value="5.50" />
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
Array.from($(".yourclassname:checked"), a => a.value);
Select Checkbox by input name
var category_id = [];
$.each($("input[name='yourClass[]']:checked"), function(){
category_id.push($(this).val());
});
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>
function selectedValues(ele){
var arr = [];
for(var i = 0; i < ele.length; i++){
if(ele[i].type == 'checkbox' && ele[i].checked){
arr.push(ele[i].value);
}
}
return arr;
}
var array = []
$("input:checkbox[name=type]:checked").each(function(){
array.push($(this).val());
});
can use this function that I created
function getCheckBoxArrayValue(nameInput){
let valores = [];
let checked = document.querySelectorAll('input[name="'+nameInput+'"]:checked');
checked.forEach(input => {
let valor = input?.defaultValue || input?.value;
valores.push(valor);
});
return(valores);
}
to use it just call it that way
getCheckBoxArrayValue("type");
Use below code to get all checked values
var yourArray=[];
$("input[name='ordercheckbox']:checked").each(function(){
yourArray.push($(this).val());
});
console.log(yourArray);
var checked= $('input[name="nameOfCheckbox"]: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() {
var values = [];
{
$('#myDiv :checked').each(function() {
//if(values.indexOf($(this).val()) === -1){
values.push($(this).val());
// }
});
console.log(values);
}
});
<div id="myDiv">
<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" />
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></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,
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 idsComenzi = [];
$('input:checked').each(function(){
idsComenzi.push($(this).val());
});
Just adding my two cents, in case it helps someone :
const data = $checkboxes.filter(':checked').toArray().map((item) => item.value);
I already had a jQuery object, so I wouldn't select all my checkbox another time, that's why I used jQuery's filter method. Then I convert it to a JS array, and I map the array to return items'value.
This is an old question but in 2022 There is a better way to implement it using vanilla JS
We don't need react or fancy frameworks.
We just need handle two onchange events like this:
const types = [{id:1, name:'1'}, {id:2, name:'2'}, {id:3, name:'3'}, {id:4, name:'4'}, {id:5, name:'5'}, {id:6, name:'6'}]
const all = document.getElementById('select-all')
const summary = document.querySelector('p')
let selected = new Set()
const onCheck = event => {
event.target.checked ? selected.add(event.target.value) : selected.delete(event.target.value)
summary.textContent = `[${[...selected].join(', ')} | size: ${selected.size}] types selected.`
all.checked = selected.size === types.length
}
const createCBInput = t => {
const ol = document.querySelector('ol')
const li = document.createElement('li')
const input = document.createElement('input')
input.type = 'checkbox'
input.id = t.id
input.name = 'type'
input.value = t.id
input.checked = selected.has(t.id)
input.onchange = onCheck
const label = document.createElement('label')
label.htmlFor = t.id
label.textContent = t.name
li.append(input, label)
ol.appendChild(li)
}
const onSelectAll = event => {
const checked = event.target.checked
for (const t of types) {
const cb = document.getElementById(t.id)
cb.checked = checked ? true : selected.has(t.id)
const event = new Event('change')
cb.dispatchEvent(event)
}
}
all.checked = selected.size === types.length
all.onchange = onSelectAll
for (const t of types) {
createCBInput(t)
}
ol {
list-style-type: none;
padding-left: 0;
}
<ol>
<li>
<input type="checkbox" id="select-all">
<label for="select-all"><strong>Select all</strong></label>
</li>
</ol>
<p></p>
$(document).ready(function()
{
$('input[type="checkbox"]').click(function() {
var arr =[];
$('input[type="checkbox"]:checked').each(function() {
//arr.push($(this).parent('p').text()+'\n');
arr.push($(this).val()+'\n');
});
var array = arr.toString().split(',')
$("#text").val(array.join(""));
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<p>Append value when checkbox is checked</p>
<textarea rows="4" id="text" style="width: 100%">
</textarea>
<div id="checkboxes">
<p><input type="checkbox" value="Item 1"><span> Item 1</span></p>
<p><input type="checkbox" value="Item 2"><span> Item 2</span></p>
<p><input type="checkbox" value="Item 3"><span> Item 3</span></p>
<p><input type="checkbox" value="Item 4"><span> Item 4</span></p>
<p><input type="checkbox" value="Item 5"><span> Item 5</span></p>
</div>