Get multiple values out of checkboxes [duplicate] - javascript

This question already has an answer here:
Best way to get all selected checkboxes VALUES in jQuery [duplicate]
(1 answer)
Closed 5 years ago.
I searched a lot on the internet but I still can't find the right answer to my question. I am trying to "print" all the selected values out of multiple checkboxes on my html-page. However, this works only for integers and not for other values. Right now, I use to following code:
<div>
<input type="checkbox" name="options[]" value="1" />
<input type="checkbox" name="options[]" value="2" />
</div>
<div>
<input type="checkbox" name="options[]" value="2" />
<input type="checkbox" name="options[]" value="4" />
<input type="checkbox" name="options[]" value="5" />
</div>
<span></span>
in combination with the following jquery code:
function calculate() {
var arr = $.map($('input:checkbox:checked'), function(e, i) {
return +e.value;
});
$('span').text('the checked values are: ' + arr.join(','));
}
calculate();
$('div').delegate('input:checkbox', 'click', calculate);
The problem right now, is that I want to see all the values from the checkboxes, however, I do not want them to be integers, but they should have values like:
<div>
<input type="checkbox" name="options[]" value="Teamsport" />
<input type="checkbox" name="options[]" value="Individual sport" />
</div>
So that there will be an output like:
the selected values are: Teamsport,Ballsport,etc..
I think the problem should be in the Jquery code, but I am not very familiar with javascript and jquery, so I hope that someone can help me.

There is simply a typo in your code: this:
return +e.value;
must be
return e.value;
The prefix + is only defined for numbers, so javascript tries to convert the "Teamsport" into a number - which is NaN (not a number)

hier is an example may help you
$(':checkbox').change(function(){
var liste2 = $(':checkbox:checked').map(function() {
return this.value;
}).get();
$('span').text('the checked values are: ' + liste2);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
<input type="checkbox" name="options[]" value="1" />
<input type="checkbox" name="options[]" value="2" />
</div>
<div>
<input type="checkbox" name="options[]" value="3" />
<input type="checkbox" name="options[]" value="4" />
<input type="checkbox" name="options[]" value="5" />
</div>
<span></span>

The problem lies here: return +e.value;
+e.value will return NaN for non-number values, in this case, String will be converted to NaN
function calculate() {
var arr = $.map($('input:checkbox:checked'), function(e, i) {
return e.value; // +e.value will return NaN for String and non number values
});
$('span').text('the checked values are: ' + arr.join(','));
}
calculate();
$('div').delegate('input:checkbox', 'click', calculate);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
<input type="checkbox" name="options[]" value="abc" />
<input type="checkbox" name="options[]" value="pqr" />
</div>
<div>
<input type="checkbox" name="options[]" value="xyz" />
<input type="checkbox" name="options[]" value="lmn" />
<input type="checkbox" name="options[]" value="ccc" />
</div>
<span></span>

Just return the e.value in your map function.
function calculate() {
var arr = $.map($('input[type="checkbox"]:checked'), function(e, i) {
return e.value;
});
$('span').text('the checked values are: ' + arr.join(','));
// console.log('the checked values are: ' + arr.join(','))
}
calculate();
$('div').on('click', 'input:checkbox', calculate);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div>
<input type="checkbox" name="options[]" value="Teamsport" />
<input type="checkbox" name="options[]" value="Individual sport" />
</div>
<span></span>

function calculate() {
var arr =[];
$('input:checkbox:checked').each(function() {
arr.push($(this).val());
});
$('span').text('the checked values are: ' + arr.join(','));
}
calculate();
$('div').delegate('input:checkbox', 'click', calculate);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div>
<input type="checkbox" name="options[]" value="1" />
<input type="checkbox" name="options[]" value="2" />
</div>
<div>
<input type="checkbox" name="options[]" value="2" />
<input type="checkbox" name="options[]" value="4" />
<input type="checkbox" name="options[]" value="5" />
</div>
<div>
<input type="checkbox" name="options[]" value="Teamsport" />
<input type="checkbox" name="options[]" value="Individual sport" />
</div>
<span></span>

Related

How to show count of selected checkboxes in a table

Array.prototype.shuffle = function() {
let m = this.length, i;
while (m) {
i = (Math.random() * m--) >>> 0;
[this[m], this[i]] = [this[i], this[m]]
}
return this;
}
$('#select_random').on('click', function() {
if ($(this).prop('checked')) {
let minnum = 3, maxnum = 6
let rand = Math.min(maxnum, Math.floor(Math.random() * ($('.check').length - 1 - minnum)) + minnum)
//create our keys array
let keyArray = [...Array($('.check').length).keys()].shuffle().slice(0, rand)
keyArray.forEach((chk_i, i) => {
if (i < rand) $($('.check').get(chk_i)).prop('checked', true)
})
} else {
$('.check').prop('checked', false);
}
});
const selectedElm = document.getElementById('selected');
function showChecked(){
selectedElm.innerHTML = document.querySelectorAll('input[name=check]:checked').length;
}
document.querySelectorAll("input[name=check]").forEach(i=>{
i.onclick = () => showChecked();
});
Using this script to select random amount of checkboxes in table.
Want to show count number of selected checkboxes count.
Tried some sample not working. Tried this example, not working for me. Tring to get result in div span area like below.
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<label>Select Random <input type='checkbox' id="select_random"></label>
<div id="result">Total Number of Items Selected = <span id="selected">0</span></div>
<div class='cb'>
<input type="checkbox" name="check[]" class="check"> checkbox <br />
<input type="checkbox" name="check[]" class="check"> checkbox <br />
<input type="checkbox" name="check[]" class="check"> checkbox <br />
<input type="checkbox" name="check[]" class="check"> checkbox <br />
<input type="checkbox" name="check[]" class="check"> checkbox <br />
<input type="checkbox" name="check[]" class="check"> checkbox <br />
<input type="checkbox" name="check[]" class="check"> checkbox <br />
<input type="checkbox" name="check[]" class="check"> checkbox <br />
<input type="checkbox" name="check[]" class="check"> checkbox <br />
<input type="checkbox" name="check[]" class="check"> checkbox <br />
<input type="checkbox" name="check[]" class="check"> checkbox <br />
<input type="checkbox" name="check[]" class="check"> checkbox <br />
<input type="checkbox" name="check[]" class="check"> checkbox <br />
<input type="checkbox" name="check[]" class="check"> checkbox <br />
<input type="checkbox" name="check[]" class="check"> checkbox <br />
Solution
let checked = $(".check:checked");
in your case :
$(".check:checked").length // will return count of checked checkboxes;
i hope it was useful
Here is a code snippet showing how to count checked checkboxes. If I have misunderstood your problem, let me/us know and I will either alter or delete this answer
console.log(document.querySelectorAll("input:checked").length);
1<input type="checkbox" checked/>
2<input type="checkbox" checked/>
3<input type="checkbox"/>
4<input type="checkbox" checked/>
Here is one possible solution
const checkboxContainer = document.querySelector('.cb');
function showChecked(){
selectedElm.innerHTML = checkboxContainer.querySelectorAll('input[type=checkbox]:checked').length;
}
You want to limit the search to a parent container tag and also filter out by input type.

Check and summed if two or more checkbox is checked

I have an 4 input checkbox tag, and 1 div tag to display a price if one checkbox is checked
<input type="checkbox" value="None" id="check1" />
<input type="checkbox" value="None" id="check2" />
<input type="checkbox" value="None" id="check3" />
<input type="checkbox" value="None" id="check4" />
<div id="price"></div>
What i want to do if only 1 random checkbox is checked it will display number 1,800 on div#price, but if 2 checkbox is checked it will summed become 3,600 and so on until 4 checkbox. But i really confused how to do that using jQuery. Any idea?
Use :checkbox selector to assign change event on all thre type = checkbox elements, one can add [value="None"] while selecing checkbox elements to be more specific.
Use :checkbox:checked selector to select the checked checkboxes.
var val = 1800;
$(':checkbox[value="None"]').on('change', function() {
var len = $(':checkbox:checked').length;
$('#price').text(len * val);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.2/jquery.min.js"></script>
<input type="checkbox" value="None" id="check1" />
<input type="checkbox" value="None" id="check2" />
<input type="checkbox" value="None" id="check3" />
<input type="checkbox" value="None" id="check4" />
<div id="price"></div>
HTML
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.2/jquery.min.js"></script>
<input type="checkbox" value="100" id="check1" />
<input type="checkbox" value="21" id="check2" />
<input type="checkbox" value="22" id="check3" />
<input type="checkbox" value="4" id="check4" />
<div id="price"></div>
JAVASCRIPT
var price=0;
$(':checkbox').on('change', function() {
var len = parseInt(this.value);
if($(this).is(':checked')){
price+=len;
}else{
price-=len;
}
console.log(price)
$('#price').text(price);
});
JSBIN
JSBIN-URL

Calculate total on checkbox checked

HTML
<div id="catlist">
<input type="checkbox" id="cat_1" value="cat_1" price="1.5" /><label for="cat_1">cat_1</label><br/>
<input type="checkbox" id="cat_2" value="cat_2" price="2" /><label for="cat_2">cat_2</label><br/>
<input type="checkbox" id="cat_3" value="cat_3" price="3.5" /><label for="cat_3">cat_3</label><br/>
<input type="checkbox" id="cat_4" value="cat_4" price="4" /><label for="cat_4">cat_4</label><br/>
<input type="checkbox" id="cat_5" value="cat_5" price="5" /><label for="cat_5">cat_5</label><br/>
<input type="checkbox" id="cat_6" value="cat_6" price="6.5" /><label for="cat_6">cat_6</label><br/>
<input type="checkbox" id="cat_7" value="cat_7" price="7" /><label for="cat_7">cat_7</label><br/>
<input type="checkbox" id="cat_8" value="cat_8" price="8" /><label for="cat_8">cat_8</label><br/>
<input type="checkbox" id="cat_9" value="cat_9" price="9.5" /><label for="cat_9">cat_9</label>
</div>
<input type="text" id="total" value="0" />
Javascript
function calcAndShowTotal(){
var total = 0;
$('#catlist :checkbox[checked]').each(function(){
total =+ parseFloat($(this).attr('price')) || 0;
});
$('#total').val(total);
}
$('#pricelist :checkbox').click(function(){
calcAndShowTotal();
});
calcAndShowTotal();
I am getting particular value. WHY? I tried sum of total, i tried jquery but no success..
Use $('#catlist :checkbox:checked') selector to select checked check-boxes
[] is used as attribute selector and it could be used as '[type="checkbox"]' but it will not filter checked check-boxes
+ operator is not needed before parseFloat, it has to be total =+
Instead of calling handler, just invoke change handler using .change()
function calcAndShowTotal() {
var total = 0;
$('#catlist :checkbox:checked').each(function() {
total += parseFloat($(this).attr('price')) || 0;
});
$('#total').val(total);
}
$('#catlist :checkbox').change(calcAndShowTotal).change();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<div id="catlist">
<input type="checkbox" id="cat_1" value="cat_1" price="1.5" />
<label for="cat_1">cat_1</label>
<br/>
<input type="checkbox" id="cat_2" value="cat_2" price="2" />
<label for="cat_2">cat_2</label>
<br/>
<input type="checkbox" id="cat_3" value="cat_3" price="3.5" />
<label for="cat_3">cat_3</label>
<br/>
<input type="checkbox" id="cat_4" value="cat_4" price="4" />
<label for="cat_4">cat_4</label>
<br/>
<input type="checkbox" id="cat_5" value="cat_5" price="5" />
<label for="cat_5">cat_5</label>
<br/>
<input type="checkbox" id="cat_6" value="cat_6" price="6.5" />
<label for="cat_6">cat_6</label>
<br/>
<input type="checkbox" id="cat_7" value="cat_7" price="7" />
<label for="cat_7">cat_7</label>
<br/>
<input type="checkbox" id="cat_8" value="cat_8" price="8" />
<label for="cat_8">cat_8</label>
<br/>
<input type="checkbox" id="cat_9" value="cat_9" price="9.5" />
<label for="cat_9">cat_9</label>
</div>
<input type="text" id="total" value="0" />
Using Array#reduce
function calcAndShowTotal() {
var total = [].reduce.call($('#catlist :checkbox:checked'), function(a, b) {
return a + +$(b).attr('price') || 0;
}, 0);
$('#total').val(total);
}
$('#catlist :checkbox').change(calcAndShowTotal).change();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<div id="catlist">
<input type="checkbox" id="cat_1" value="cat_1" price="1.5" />
<label for="cat_1">cat_1</label>
<br/>
<input type="checkbox" id="cat_2" value="cat_2" price="2" />
<label for="cat_2">cat_2</label>
<br/>
<input type="checkbox" id="cat_3" value="cat_3" price="3.5" />
<label for="cat_3">cat_3</label>
<br/>
<input type="checkbox" id="cat_4" value="cat_4" price="4" />
<label for="cat_4">cat_4</label>
<br/>
<input type="checkbox" id="cat_5" value="cat_5" price="5" />
<label for="cat_5">cat_5</label>
<br/>
<input type="checkbox" id="cat_6" value="cat_6" price="6.5" />
<label for="cat_6">cat_6</label>
<br/>
<input type="checkbox" id="cat_7" value="cat_7" price="7" />
<label for="cat_7">cat_7</label>
<br/>
<input type="checkbox" id="cat_8" value="cat_8" price="8" />
<label for="cat_8">cat_8</label>
<br/>
<input type="checkbox" id="cat_9" value="cat_9" price="9.5" />
<label for="cat_9">cat_9</label>
</div>
<input type="text" id="total" value="0" />
Instead of looping you can use change which will respond to and change event on the checkbox. Also you need add or subtract value like this += for addition on -= for subtraction
var _total = 0;
$('input[type="checkbox"]').change(function() {
if($(this).is(':checked')){
_total += parseFloat($(this).attr('price')) || 0;
}
else{
_total -= parseFloat($(this).attr('price')) || 0;
}
$('#total').val(_total);
})
JSFIDDLE
$('input:checkbox').change(function(){
var totalprice=0;
$('input:checkbox:checked').each(function(){
totalprice+= parseFloat($(this).attr('price'));
});
$('#total').val(totalprice)
});

html & javascript: multiple checkboxes run same function for multiple textboxes

I want chkbox1 to call a javascript function for txtbox1, chkbox2 to call the same function but for txtbox2, and so on.
To take it a step further, I want all checkboxes checked in their default state and I want the functions to run when unchecked.
How can I achieve this?
I only know simple way for one checkbox:
function OnChangeCheckbox(checkbox) {
if (checkbox.checked) {
alert("The check box is checked.");
} else {
alert("The check box is not checked.");
}
}
<input type="checkbox" value="yes" checked onclick="OnChangeCheckbox (this)" />
<label for="checkbox">uncheck box</label>
If your checkboxes and textboxes have something in common then you can do something like this:
<input type="checkbox" checked id="chk1" onclick="myFunction(this)" />
<input type="checkbox" checked id="chk2" onclick="myFunction(this)" />
<input type="checkbox" checked id="chk3" onclick="myFunction(this)" />
<input type="checkbox" checked id="chk4" onclick="myFunction(this)" />
<input type="text" id="txt1" />
<input type="text" id="txt2" />
<input type="text" id="txt3" />
<input type="text" id="txt4" />
<script>
function myFunction(el) {
var txt = document.getElementById(el.id.replace('chk', 'txt'));
if(el.checked) {
txt.value = 'checked';
}
else
txt.value = 'unchecked';
}
</script>
function myFunction(el) {
var txt = document.getElementById(el.id.replace('chk', 'txt'));
if(el.checked) {
txt.value = 'checked';
}else{
txt.value = 'unchecked';
}
}
<div>
<input type="checkbox" checked id="chk1" onclick="myFunction(this)" />
<input type="text" id="txt1" />
</div>
<div>
<input type="checkbox" checked id="chk2" onclick="myFunction(this)" />
<input type="text" id="txt2" />
</div>
<div>
<input type="checkbox" checked id="chk3" onclick="myFunction(this)" />
<input type="text" id="txt3" />
</div>
<div>
<input type="checkbox" checked id="chk4" onclick="myFunction(this)" />
<input type="text" id="txt4" />
</div>
You can create separate functions
function OnChangeCheckbox1(checkbox) {
..
}
<input type="checkbox" value="yes" checked onclick="OnChangeCheckbox1(this)" />
<label for="checkbox">uncheck box</label>
function OnChangeCheckbox2(checkbox) {
..
}
<input type="checkbox" value="yes" checked onclick="OnChangeCheckbox2 (this)" />
<label for="checkbox">uncheck box</label>
Update Answer
hi, i just update my answer, so your function run if unchecked and get the value of checkbox
<input type="checkbox" checked value="1" onclick="myFunction(this)" />
<input type="checkbox" checked value="2" onclick="myFunction(this)" />
<input type="checkbox" checked value="3" onclick="myFunction(this)" />
<input type="checkbox" checked value="4" onclick="myFunction(this)" />
<script>
function myFunction(e) {
if(e.checked == false) {
alert('this box unchecked | value = ' + e.value);
}
}
</script>
<div class="check_filter">
<div id="filter">
<input type="checkbox" id="check1" /><label for="check1">XYZ</label>
<input type="checkbox" id="check2" /><label for="check2">WAS</label>
<input type="checkbox" id="check3" /><label for="check3">DEF</label>
</div>
</div>
Js code :
$(document).ready(function() {
$(":checkbox").click(function(){
var id = $(this).attr('id');
var isChecked = $(this).attr('checked'));
if(isChecked == false){
switch (id) {
case check1:
txtbox1();
break;
case check2:
txtbox2();
break;
default:
defaultFunction();
}
}
});
});

Want to give different ID to each element

I want to add HTML tag into the values.
http://jsfiddle.net/iamakshay04/seyzta8c/1/
Above is the fiddle. When checkbox is clicked, the values are printed, I want to print each value as a different html element. <p>1</p> <p>2</p> <p>3</p>
$('.ads_Checkbox').click(function() {
var sel = $('input[type=checkbox]:checked').map(function(_, el) {
return $(el).val();
}).get();
document.getElementById("demo").innerHTML = sel;
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="ad_Checkbox1" class="ads_Checkbox" type="checkbox" value="1" />
<input id="ad_Checkbox2" class="ads_Checkbox" type="checkbox" value="2" />
<input id="ad_Checkbox3" class="ads_Checkbox" type="checkbox" value="3" />
<input id="ad_Checkbox4" class="ads_Checkbox" type="checkbox" value="4" />
<input type="button" id="save_value" name="save_value" value="Save" />
<p id="demo">
</p>
If you want to show values as different elements then try below where you can add paragraphs at the time of reading the values.
$('.ads_Checkbox').click(function() {
var sel = $('input[type=checkbox]:checked').map(function(_, el) {
return "<p>"+ $(el).val() + "</p>";
}).get();
document.getElementById("demo").innerHTML = sel;
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="ad_Checkbox1" class="ads_Checkbox" type="checkbox" value="1" />
<input id="ad_Checkbox2" class="ads_Checkbox" type="checkbox" value="2" />
<input id="ad_Checkbox3" class="ads_Checkbox" type="checkbox" value="3" />
<input id="ad_Checkbox4" class="ads_Checkbox" type="checkbox" value="4" />
<input type="button" id="save_value" name="save_value" value="Save" />
<p id="demo">
</p>
This will give you the different elements:-
$('.ads_Checkbox').change(function() {
var sel = $('input[type=checkbox]:checked').map(function(_, el) {
return $('<p></p>').html($(el).val());
}).get();
$("#demo").html(sel);
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="ad_Checkbox1" class="ads_Checkbox" type="checkbox" value="1" />
<input id="ad_Checkbox2" class="ads_Checkbox" type="checkbox" value="2" />
<input id="ad_Checkbox3" class="ads_Checkbox" type="checkbox" value="3" />
<input id="ad_Checkbox4" class="ads_Checkbox" type="checkbox" value="4" />
<input type="button" id="save_value" name="save_value" value="Save" />
<p id="demo">
</p>

Categories

Resources