I have simple js script that adds input values in array after clicking on input, it works as expected except that it duplicates values every time I'm clicking on another input, i.e. I click on input with value 5, array now is ["5"] then I click on input with value 4 and after that array is ["5", "5", "4"]. I've tried if statement with check on e.target but it didn't help. How can I add only input value on which I click, not all checked input values? Here is the link on pen. My HTML markdown:
<div>
<input type="checkbox" value="5">
<input type="checkbox" value="4">
<input type="checkbox" value="3">
<input type="checkbox" value="2">
<input type="checkbox" value="1">
</div>
<p></p>
And JS code:
let checkboxes = document.getElementsByTagName('input');
let checkboxesChecked = [];
let p = document.getElementsByTagName('p');
function getCheckedCheckBoxes(e) {
if (e.target.checked == true) {
for (let i = 0; i < checkboxes.length; i++) {
if (checkboxes[i].checked) {
checkboxesChecked.push(checkboxes[i].value);
console.log(checkboxesChecked)
}
}
p[0].innerHTML = checkboxesChecked;
return checkboxesChecked;
}
};
for (let i = 0; i < checkboxes.length; i++) {
checkboxes[i].addEventListener('click', getCheckedCheckBoxes);
}
Any help and tips would be appreciated.
You need to reset the array each time and you should not just update it when checked.
let checkboxes = document.getElementsByTagName('input');
let checkboxesChecked = [];
let p = document.getElementsByTagName('p');
function getCheckedCheckBoxes(e) {
checkboxesChecked.length = 0;
for (let i = 0; i < checkboxes.length; i++) {
if (checkboxes[i].checked) {
checkboxesChecked.push(checkboxes[i].value);
console.log(checkboxesChecked)
}
}
p[0].innerHTML = checkboxesChecked;
return checkboxesChecked;
}
for (let i = 0; i < checkboxes.length; i++) {
checkboxes[i].addEventListener('click', getCheckedCheckBoxes);
}
<div>
<input type="checkbox" value="5">
<input type="checkbox" value="4">
<input type="checkbox" value="3">
<input type="checkbox" value="2">
<input type="checkbox" value="1">
</div>
<p></p>
Personally I would use querySelectorAll
let checkboxes = document.getElementsByTagName('input');
let checkboxesChecked = [];
let p = document.getElementsByTagName('p');
function getCheckedCheckBoxes(e) {
checkboxesChecked = Array.from(document.querySelectorAll("input:checked")).map(cb => cb.value)
p[0].innerHTML = checkboxesChecked;
}
for (let i = 0; i < checkboxes.length; i++) {
checkboxes[i].addEventListener('click', getCheckedCheckBoxes);
}
<div>
<input type="checkbox" value="5">
<input type="checkbox" value="4">
<input type="checkbox" value="3">
<input type="checkbox" value="2">
<input type="checkbox" value="1">
</div>
<p></p>
With your comments.... which still does not make sense with checkboxes, they should be buttons.
let checkboxes = document.getElementsByTagName('input');
let checkboxesChecked = [];
let p = document.getElementsByTagName('p');
function getCheckedCheckBoxes(e) {
if (e.target.checked) checkboxesChecked.push(e.target.value)
p[0].innerHTML = checkboxesChecked;
}
for (let i = 0; i < checkboxes.length; i++) {
checkboxes[i].addEventListener('click', getCheckedCheckBoxes);
}
<div>
<input type="checkbox" value="5">
<input type="checkbox" value="4">
<input type="checkbox" value="3">
<input type="checkbox" value="2">
<input type="checkbox" value="1">
</div>
<p></p>
You've said you want it to add the number that was clicked each time it's clicked to become checked, so if I click 5 (on) it's ["5"], then if I click it again (off) there's no change, and if I click it a third time we add "5" again for ["5", "5"]. If so:
function getCheckedCheckBoxes(e) {
if (e.target.checked) {
checkboxesChecked.push(e.target.value);
}
p[0].innerHTML = checkboxesChecked;
return checkboxesChecked;
}
Live Example:
let checkboxes = document.getElementsByTagName('input');
let checkboxesChecked = [];
let p = document.getElementsByTagName('p');
function getCheckedCheckBoxes(e) {
if (e.target.checked) {
checkboxesChecked.push(e.target.value);
}
p[0].innerHTML = checkboxesChecked;
return checkboxesChecked;
}
for (let i = 0; i < checkboxes.length; i++) {
checkboxes[i].addEventListener('click', getCheckedCheckBoxes);
}
<div>
<input type="checkbox" value="5">
<input type="checkbox" value="4">
<input type="checkbox" value="3">
<input type="checkbox" value="2">
<input type="checkbox" value="1">
</div>
<p></p>
Related
I have a group of check boxes with same name, what I need is when I click any one of them, other checkboxes must get disabled. how should I apply Javascript over it?
<input type="checkbox" name="finallevelusers[]" value="1"/>
<input type="checkbox" name="finallevelusers[]" value="1"/>
<input type="checkbox" name="finallevelusers[]" value="1"/>
<input type="checkbox" name="finallevelusers[]" value="1"/>
Please help...
You could do
$('input').attr('disabled',true);
...if you really need it. But you might be better off using radio buttons.
Try the demo
<script type="text/javascript">
for (i=0; i<document.test.finallevelusers.length; i++){
if (document.test.finallevelusers[i].checked !=true)
document.test.finallevelusers[i].disabled='true';
}
</script>
probably you want them enabled again when user uncheck the checkbox
for (i=0; i<document.test.finallevelusers.length; i++){
if (document.test.finallevelusers[i].disabled ==true)
document.test.finallevelusers[i].disabled='false';
}
<script type="text/javascript">
function disableHandler (form, inputName) {
var inputs = form.elements[inputName];
for (var i = 0; i < inputs.length; i++) {
var input = inputs[i];
input.onclick = function (evt) {
if (this.checked) {
disableInputs(this, inputs);
}
else {
enableInputs(this, inputs);
}
return true;
};
}
}
function disableInputs (input, inputs) {
for (var i = 0; i < inputs.length; i++) {
var currentInput = inputs[i];
if (currentInput != input) {
currentInput.disabled = true;
}
}
}
function enableInputs (input, inputs) {
for (var i = 0; i < inputs.length; i++) {
var currentInput = inputs[i];
if (currentInput != input) {
currentInput.disabled = false;
}
}
}
</script>
</head>
<body>
<form name="aForm" action="">
<p>
<label>
<input type="checkbox" name="finallevelusers[]" value="1">
</label>
<label>
<input type="checkbox" name="finallevelusers[]" value="1">
</label>
<label>
<input type="checkbox" name="finallevelusers[]" value="1">
</label>
</p>
</form>
<script type="text/javascript">
disableHandler(document.forms.aForm, 'finallevelusers[]');
</script>
Hope This solution helps you-
your DOM could be something like this :
<div class="checkboxes">
<input type="checkbox" name="sameCheck" class="checkbox" id="1" onchange="checkChange()">
<input type="checkbox" name="sameCheck" class="checkbox" id="2" onchange="checkChange()">
<input type="checkbox" name="sameCheck" class="checkbox" id="3" onchange="checkChange()">
<input type="checkbox" name="sameCheck" class="checkbox" id="4" onchange="checkChange()">
</div>
And your logic is this :
let checkbox = document.querySelectorAll('.checkbox')
let b = false;
function checkChange(){
b = !b
if(b){
for(let i = 0 ; i< checkbox.length; i++){
if(checkbox[i].checked === false){
checkbox[i].disabled = 'true';
}
}
}else{
for(let i = 0 ; i< checkbox.length; i++){
checkbox[i].removeAttribute('disabled');
}
}
}
Try code like this
<script>
function uncheck(){
for(var ii=1; ii<=4; ii++){
if(document.getElementById("q6_"+ii).checked==true){
document.getElementById("q6_"+ii).checked=false;
}
}
}
</script>
i have this code in html
<input type="checkbox" value="12" id="logo" checked onchange="calculate(this);">
<input type="checkbox" value="19" id="bc" checked onchange="calculate(this);">
<input type="checkbox" value="200" id="first" onchange="calculate(this);">
<input type="checkbox" value="250" id="second" onchange="calculate(this);">
<p id="total"></p>
and then the js
var total = 0;
function calculate(option) {
if (option.checked) {
total += Number(option.value);
} else {
total -= Number(option.value);
}
document.getElementById("total").innerHTML = total;
}
i need the first two checked checkboxes to sum up from start when page loads
and after the behavior of js to get me to 0 or to total of checkboxes when checking respectively unchecking
You could add an eventlistener to the page loading and just select the options using querySelectorAll("input[type=checkbox]") which selects all checkboxes, iterarate over them and sum them up.
var total = 0;
function calculate(option) {
if (option.checked) {
total += Number(option.value);
} else {
total -= Number(option.value);
}
document.getElementById("total").innerHTML = total;
}
window.addEventListener("load", function() {
var options = document.querySelectorAll("input[type=checkbox]");
for (var i = 0; i < options.length; i++) {
const o = options[i];
if (o.checked) total += Number(o.value);
}
document.getElementById("total").innerHTML = total;
}, false);
<input type="checkbox" value="12" id="logo" checked onchange="calculate(this);">
<input type="checkbox" value="19" id="bc" checked onchange="calculate(this);">
<input type="checkbox" value="200" id="first" onchange="calculate(this);">
<input type="checkbox" value="250" id="second" onchange="calculate(this);">
<p id="total"></p>
Use a class:
<input type="checkbox" value="12" id="logo" class='summary' checked>
<input type="checkbox" value="19" id="bc" class='summary' checked>
<input type="checkbox" value="200" id="first" class='summary'>
<input type="checkbox" value="250" id="second" class='summary'>
document.addEventListener('DOMContentLoaded', function() {
var summerizers = document.querySelectorAll('.summary'),
counter = document.getElementById('counter');
for (var i = 0, c = summerizers.length; i < c; i++) {
summerizers[i].addEventListener('change', count);
}
count();
function count() {
var total = 0;
for (var i = 0, c = summerizers.length; i < c; i++) {
if (summerizers[i].checked) {
total += parseInt(summerizers[i].value, 10);
}
}
counter.value = total;
}
});
https://jsfiddle.net/r1khjrsd/
You can call the function, then recall the function onchange event. Don't need to pass this as parameter
function calculate() {
total = 0;
elements = document.getElementsByTagName('input');
for (let i = 0; i < elements.length; i++) {
if (elements[i].checked) {
total += Number(elements[i].value);
}
}
document.getElementById('total').innerHTML = total;
}
calculate();
<input type="checkbox" value="12" id="logo" checked onchange="calculate();">
<input type="checkbox" value="19" id="bc" checked onchange="calculate();">
<input type="checkbox" value="200" id="first" onchange="calculate();">
<input type="checkbox" value="250" id="second" onchange="calculate();">
<p id="total"></p>
To achieve expected result, use initial flag checking initial page load and checkTotal function to checked boxes on initial load
Steps:
Function checkedTotal to check all checked checkboxes and call calculate function with boolean value start
If start is true, only add checked checkbox values and restrict else part in calculate functionenter code here
code sample - https://codepen.io/nagasai/pen/XEyqEd?editors=1111
var total = 0;
function calculate(option,start) {
if (option.checked) {
total += Number(option.value);
} else {
if(!start){
total -= Number(option.value);
}
}
document.getElementById("total").innerHTML = total;
}
function checkedTotal(){
var checkList = document.getElementsByTagName('input');
for(var i =0; i < checkList.length; i++){
calculate(checkList[i], true)
}
}
checkedTotal()
<input type="checkbox" value="12" id="logo" checked onchange="calculate(this);">
<input type="checkbox" value="19" id="bc" checked onchange="calculate(this);">
<input type="checkbox" value="200" id="first" onchange="calculate(this);">
<input type="checkbox" value="250" id="second" onchange="calculate(this);">
<p id="total"></p>
I want to make a custom cricket team and select multiple players from different teams and then displaying them
function getMultipleCheckbox(inputdata) {
var selectedItems = [];
var count = 0;
for (var i = 0; i < inputdata.length; i++) {
if (inputdata[i].checked) {
selectedItems[count] = inputdata[i].value;
count++;
}
}
for (var loop = 0; loop < selectedItems.length; loop++) {
console.log(selectedItems[loop]);
}
return selectedItems;
}
<p>Select players</p>
<form>
<input type="checkbox" name="owns" value="player1">player1<br/>
<input type="checkbox" name="owns" value="player2">player2<br/>
<input type="checkbox" name="owns" value="player3">player3<br/>
<input type="checkbox" name="owns" value="player4">player4<br/>
<input type="checkbox" name="owns" value="player5">player5<br/>
<input type="checkbox" name="owns" value="player6">player6<br/>
<input type="button" value="Get Values" onclick="getMultipleCheckbox(this.form.owns);" />
</form>
I am running this code and it returns me set of values which are checked
var a = [];
var cboxes = $('input[name="suppcheck[]"]:checked');
var len = cboxes.length;
for (var i=0; i<len; i++) {
a[i] = cboxes[i].value;
//document.getElementByName('suppgrp[]').value = a[i];
}
I have a hidden field with ID suppgrp where I want to push all these values retrieved and wanted to pass it in array..
But I am not able to...where am I going wrong?
i have added some extra code which when page load then will call this function and also when change checkbox value then also call this function so all time it will work
loadCheck(); // initial call this function to load data
$('input[type="checkbox"]').change(function()
{
loadCheck();
});
function loadCheck() {
$('#hiddenValue').val('');
$('#showValue').val('');
var checkboxes = $('input[name="suppcheck[]"]:checked');
var data = [];
var len = checkboxes.length;
for (var i=0; i<len; i++) {
data[i] = checkboxes[i].value;
}
$('#hiddenValue').val(data);
$('#showValue').val(data);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
<input type="checkbox" name="suppcheck[]" value="1" />
<input type="checkbox" name="suppcheck[]" value="2" />
<input type="checkbox" name="suppcheck[]" value="3" />
<input type="checkbox" name="suppcheck[]" value="4" />
<input type="checkbox" name="suppcheck[]" value="5" />
<input type="checkbox" name="suppcheck[]" value="6" />
<input type="checkbox" name="suppcheck[]" value="7" />
<input type="checkbox" name="suppcheck[]" value="8" />
<input type="checkbox" name="suppcheck[]" value="9" />
<input type="hidden" id="hiddenValue" />
<input type="text" id="showValue" />
</form>
var a = [];
jQuery('input[type="checkbox"]').change(function()
{
var cboxes = jQuery('input[name="suppcheck[]"]:checked');
var len = cboxes.length;
var alval = '';
for (var i=0; i<len; i++) {
a[i] = cboxes[i].value;
if (alval != '') {
alval += ','+a[i];
}else{
alval = a[i];
}
}
jQuery('#myhidden').val(alval);
});
I can able to load value from databases to text-box...so now named as auto..from this i want to create a auto search with multiple check box to select multiple value in text-box java script...its possible ...??
<form name="form1">
<input type="checkbox" name="checkboxname" value="a">
<input type="checkbox" name="checkboxname" value="b">
<input type="checkbox" name="checkboxname" value="c">
</form>
<form name="form2">
<input type="text" name="textname">
</form>
var textbox = document.getElementsByName("textname")[0];
var checkboxes = document.getElementsByName("checkboxname");
for (var i = 0; i < checkboxes.length; i++) {
var checkbox = checkboxes[i];
checkbox.onclick = (function(chk){
return function() {
var value = "";
for (var j = 0; j < checkboxes.length; j++) {
if (checkboxes[j].checked) {
if (value === "") {
value += checkboxes[j].value;
} else {
value += "," + checkboxes[j].value;
}
}
}
textbox.value = value;
}
})(checkbox);
}
Try this,
<form name="form1" class="form_chk">
<input type="checkbox" name="checkboxname" value="a" class="chk_box">a
<input type="checkbox" name="checkboxname" value="b" class="chk_box">b
<input type="checkbox" name="checkboxname" value="c" class="chk_box">c
</form>
$( "#txt_search" ).blur(function(e) {
var $search = $(e.currentTarget),
search_str = $search.val().toLowerCase(), $chk,
$chk_ele = $('.chk_box').filter(function(index, chk){
if($(chk).val().toLowerCase().search(search_str) !== -1){
return $(chk);
}
});
$('.chk_box').prop('checked', false);
$chk_ele.prop('checked', true);
});
See the output : http://jsfiddle.net/J7dUz/