javascript checkbox un-check is not working - javascript

I have an issue in this javascript code. This code display multiple checked values, but when I unchecked any value it removes all the values from the result. I want to remove only specific unchecked value from the result. Please any one help me.
<script>
window.addEventListener('DOMContentLoaded', function (event) {
var boxes = document.querySelectorAll('#the_form input[type="checkbox"]'),
area = document.getElementById('text'), i;
for (i = 0; i < boxes.length; i += 1) {
boxes[i].addEventListener('change', function (event) {
var e = event.target;
if (e.checked) {
area.value += e.value + '\n',' ';
} else {
area.value ="";
}
}, false);
} }, false);
</script>
HTML
<form action='search1.php' method='GET' id="the_form">
</br>
<tr>
<h2>Select your problem</h2> <b>Do you have difficulty in sleeping?</b>
<input type="checkbox" id='check1' value="Difficulty sleeping">YES/NO<br>
<b>Do you feel dizziness?</b>
<input type="checkbox" id='check1' value="Dizziness ">YES/NO<br>
<b>Do you feel fever?</b>
<input type="checkbox" id='check1' onClick='check()' value='Fever'>YES/NO<br>
<b>Do you have headache?</b>
<input type="checkbox" id='check1' onClick='check()' value='Headache '>YES/NO<br>
<b>Do you feel warm to touch?</b>
<input type="checkbox" id='check1' onClick='check()' value='Warm to touch'>YES/NO<br>
<b>Do you have itching or burning issue?</b>
<input type="checkbox" id='check1' onClick='check()' value='Itching or burning'>YES/NO<br>
<b>Do you have bleeding issue?</b>
<input type="checkbox" id='check1' onClick='check()' value='Bleeding '>YES/NO<br> <br>
<input type='text'id="text" size='100' name='search' ></br></br>
</tr>
<input type='submit' name='submit' value='Search' ></br></br></br>
</form>

The problem is that you're setting area.value = "" whenever you encounter an unchecked box, so this drops all the values from boxes before it. You should initialize the value to the empty string before the loop, and then add only the checked values.
You also have to loop over all the checkboxes in the event handler, not just the checkbox you clicked on, so you can get all the checked values.
window.addEventListener('DOMContentLoaded', function (event) {
var boxes = document.querySelectorAll('#the_form input[type="checkbox"]'),
area = document.getElementById('text'), i;
for (var i = 0; i < boxes.length; i += 1) {
boxes[i].addEventListener('change', function (event) {
area.value = "";
for (var j = 0; j < boxes.length; j++) {
if (boxes[j].checked) {
area.value += boxes[j].value + '\n';
}
}
}, false);
}
}, false);
DEMO

Related

How get the sum of all the checkbox values of checked items

let addonCheckboxes = document.querySelectorAll(".custom-checkbox")
let priceSection = document.getElementById("priceSection")
let customProductPricing = document.getElementById("customProductPricing")
for (let i = 0; i < addonCheckboxes.length; i++) {
addonCheckboxes[i].addEventListener("change", function() {
if (addonCheckboxes[i].checked != false) {
priceSection.textContent = parseInt(customProductPricing) + parseInt(addonCheckboxes[i].getAttribute("price"));
} else {
priceSection.textContent = parseInt(customProductPricing)
}
})
}
<input class="custom-checkbox" type="checkbox" price="150"></input>
<input class="custom-checkbox" type="checkbox" price="150"></input>
<input class="custom-checkbox" type="checkbox" price="150"></input>
<div id="priceSection">
</id>
<div id="customProductPricing">"150"</div>
I want to get the total of all the checkboxes if they are all checked. So far it gives only one value. And need to deduct the prices if the checkbox is unchecked.
This one has fixed all the errors you made in your markup, and simplified the code by alot.
const output = document.getElementById('priceSection');
const totalPrice = () => [...document.querySelectorAll('#prices input[type=checkbox]:checked')]
.reduce((acc, {
dataset: {
price
}
}) => acc + +price, 0);
document.getElementById('prices').addEventListener('change', () => output.textContent = totalPrice());
<div id="prices">
<input type="checkbox" data-price="10" />
<input type="checkbox" data-price="20" />
<input type="checkbox" data-price="30" />
</div>
<div id="priceSection"></div>
You are overwriting instead of summing. When you are iterating through an array of checkboxes and you find that more than one is checked your function fails.
You should firstly count the sum of checked checkboxes and then send it to priceSection, and when your sum is equal to zero you should set it parseInt(customProductPricing) like you did in else.
When the change event of the <input> elements is triggered, the update() method is called and the values in the page are collected and printed on the page. I don't understand the issue of lowering the price if the checkbox is not selected. Update the update() method to subtract unselected values from the total using the following approach; Add an else statement to the if block.
(function() {
let addonCheckboxes = document.querySelectorAll(".custom-checkbox");
function update()
{
let total = parseInt(document.getElementById("customProductPricing").textContent);
for(let i = 0 ; i < addonCheckboxes.length ; ++i)
if(addonCheckboxes[i].checked == true)
total += parseInt(addonCheckboxes[i].value);
document.getElementById("priceSection").innerHTML = "Result: " + total;
}
for(let i = 0 ; i < addonCheckboxes.length ; ++i)
addonCheckboxes[i].addEventListener("change", update);
})();
<input class="custom-checkbox" type="checkbox" value="10"/>
<label>10</label>
<input class="custom-checkbox" type="checkbox" value="20"/>
<label>20<label>
<input class="custom-checkbox" type="checkbox" value="30"/>
<label>30<label>
<!-- Static Value -->
<div id="customProductPricing">40</div>
<br><div id="priceSection" style="color: red;">Result: </div>
Using data set you can access price
let addonCheckboxes = document.querySelectorAll(".custom-checkbox")
let priceSection = document.getElementById("priceSection")
let customProductPricing = document.getElementById("customProductPricing")
let sum = 0
for (let i = 0; i < addonCheckboxes.length; i++) {
addonCheckboxes[i].addEventListener("change", function(e) {
console.log(e.target.dataset.price)
if (addonCheckboxes[i].checked != false) {
sum = sum +Number(e.target.dataset.price)
} else {
sum = sum -Number(e.target.dataset.price)
}
customProductPricing.innerHTML = sum
})
}
<input class="custom-checkbox" type="checkbox" data-price="150"></input>
<input class="custom-checkbox" type="checkbox" data-price="150"></input>
<input class="custom-checkbox" type="checkbox" data-price="150"></input>
<div id="priceSection">
</id>
<div id="customProductPricing">"150"</div>
As #Sercan has mentioned... I am also not sure about the issue of loweing the sum but I've whipped up something for you.
Hopefully it'll lead you to what you want to achieve.
let addonCheckboxes = document.querySelectorAll(".custom-checkbox")
let priceSection = document.getElementById("priceSection")
let customProductPricing = document.getElementById("customProductPricing");
var checkboxes = document.getElementsByClassName("custom-checkbox");
function sum(){
var total = 0;
for(let x = 0; x < checkboxes.length; x++){
let price = document.getElementsByClassName(x);
if(price[0].checked){
total = total + Number(price[0].dataset.price);
}
}
console.log('Sum = ' + total)
}
<input class="custom-checkbox 0" onclick="sum()" type="checkbox" data-price="150"></input>
<input class="custom-checkbox 1" onclick="sum()" type="checkbox" data-price="150"></input>
<input class="custom-checkbox 2" onclick="sum()" type="checkbox" data-price="150"></input>
<div id="priceSection"></id>
<div id="customProductPricing">"150"</div>

Disable checkbox after reaching a limit

I'm looking for a native JavaScript Solution that will prevent the user checking more than 2 items by disabling the remaining checkboxes (and enabling them again if the user unchecks one of their options)
Below are the checkboxes I have in place:
<div class="checkboxdiv">
<input type="hidden" name="Extras" value="">
<input type="checkbox" name="Extras" value="Wedges"><label>Wedges</label> <br/>
<input type="checkbox" name="Extras" value="Chips"><label>Chips</label> <br/>
<input type="checkbox" name="Extras" value="Garlic Bread"><label>Garlic Bread</label> <br/>
<input type="checkbox" name="Extras" value="Chicken Wings"><label>Chicken Wings</label> <br/>
<input type="checkbox" name="Extras" value="Cheese Sticks"><label>Cheese Sticks</label>
</div>
I am aware this has been covered using JQuery, but I'm looking for a native solution so I can better understand how the code works.
Solution
This is the final solution I have come up with, through everyone's help.
function checkboxlimit(checkgroup, limit){
var checkgroup=checkgroup;
var limit=limit;
//Changes onclick funtion for each checkbox
for (var i=0; i<checkgroup.length; i++){
checkgroup[i].onclick= function(){
var checkedcount=0;
//Loops through checkboxes
for (var i=0; i<checkgroup.length; i++){
//adds 1 if checked, 0 if not
checkedcount+=(checkgroup[i].checked)? 1 : 0;
}
//Loops through checkboxes
for (var i=0; i<checkgroup.length; i++){
//Disables check box if it's unchecked and the limit has been reached
if(!checkgroup[i].checked && checkedcount==limit){
checkgroup[i].disabled=true;
}
//Enables all checkboxes otherwise
else{
checkgroup[i].disabled=false;
}
}
}
}
}
Check out the CSS pseudo class ":checked" and document.querySelectorAll.
Here is a fiddle to start from:
var currentlyCheckedCount = 0
function disableRemainingCheckboxes() {
Array.from(document.querySelectorAll('input[type="checkbox"]:not(:checked)')).forEach(function(element) {
element.disabled = 'disabled'
})
}
function enableAllCheckboxes() {
Array.from(document.querySelectorAll('input[type="checkbox"]')).forEach(function(element) {
element.disabled = undefined
})
}
Array.from(document.querySelectorAll("input[type='checkbox']")).forEach(function(checkbox) {
checkbox.addEventListener('change', onCheckboxClick)
})
function onCheckboxClick() {
if(this.checked) {
currentlyCheckedCount++
} else {
currentlyCheckedCount--
}
if(currentlyCheckedCount == 2) {
disableRemainingCheckboxes()
} else {
enableAllCheckboxes()
}
}
Geekonaut answer/code is great, but, if you care about IE support (Array.from() doesn't work in it), here is simplified, more straight-forward version:
limit = 0; //set limit
checkboxes = document.querySelectorAll('.checkboxdiv input[type="checkbox"]'); //select all checkboxes
function checker(elem) {
if (elem.checked) { //if checked, increment counter
limit++;
} else {
limit--; //else, decrement counter
}
for (i = 0; i < checkboxes.length; i++) { // loop through all
if (limit == 2) {
if (!checkboxes[i].checked) {
checkboxes[i].disabled = true; // and disable unchecked checkboxes
}
} else { //if limit is less than two
if (!checkboxes[i].checked) {
checkboxes[i].disabled = false; // enable unchecked checkboxes
}
}
}
}
for (i = 0; i < checkboxes.length; i++) {
checkboxes[i].onclick = function() { //call function on click and send current element as param
checker(this);
}
}
<div class="checkboxdiv">
<input type="hidden" name="Extras" value="">
<input type="checkbox" name="Extras" value="Wedges"><label>Wedges</label> <br/>
<input type="checkbox" name="Extras" value="Chips"><label>Chips</label> <br/>
<input type="checkbox" name="Extras" value="Garlic Bread"><label>Garlic Bread</label> <br/>
<input type="checkbox" name="Extras" value="Chicken Wings"><label>Chicken Wings</label> <br/>
<input type="checkbox" name="Extras" value="Cheese Sticks"><label>Cheese Sticks</label>
</div>
Code is very clear (easy to understand), i hope, and there are comments, too.

Disable button if all checkboxes are unchecked

I have a list of checkboxes, and I need to disable my submit button if none of them are checked, and enable it as soon as at least one gets checked. I see lots of advice for doing this with just a single checkbox, but I'm hung up on getting it to work with multiple checkboxes. I want to use javascript for this project, even though I know there are a bunch of answers for jquery. Here's what I've got - it works for the first checkbox, but not the second.
HTML:
<input type="checkbox" id="checkme"/> Option1<br>
<input type="checkbox" id="checkme"/> Option2<br>
<input type="checkbox" id="checkme"/> Option3<br>
<input type="submit" name="sendNewSms" class="inputButton" disabled="disabled" id="sendNewSms" value=" Send " />
Javascript:
var checker = document.getElementById('checkme');
var sendbtn = document.getElementById('sendNewSms');
// when unchecked or checked, run the function
checker.onchange = function(){
if(this.checked){
sendbtn.disabled = false;
} else {
sendbtn.disabled = true;
}
}
I'd group your inputs in a container and watch that for events using addEventListener. Then loop through the checkboxes, checking their status. Finally set the button to disabled unless our criteria is met.
var checks = document.getElementsByName('checkme');
var checkBoxList = document.getElementById('checkBoxList');
var sendbtn = document.getElementById('sendNewSms');
function allTrue(nodeList) {
for (var i = 0; i < nodeList.length; i++) {
if (nodeList[i].checked === false) return false;
}
return true;
}
checkBoxList.addEventListener('click', function(event) {
sendbtn.disabled = true;
if (allTrue(checks)) sendbtn.disabled = false;
});
<div id="checkBoxList">
<input type="checkbox" name="checkme"/> Option1<br>
<input type="checkbox" name="checkme"/> Option2<br>
<input type="checkbox" name="checkme"/> Option3<br>
</div>
<input type="submit" name="sendNewSms" class="inputButton" disabled="disabled" id="sendNewSms" value=" Send " />
html
<input type="checkbox" class="checkme"/> Option1<br>
<input type="checkbox" class="checkme"/> Option2<br>
<input type="checkbox" class="checkme"/> Option3<br>
<input type="submit" name="sendNewSms" class="inputButton" disabled="disabled" id="sendNewSms" value=" Send " />
js
var checkerArr = document.getElementsByClassName('checkme');
var sendbtn = document.getElementById('sendNewSms');
// when unchecked or checked, run the function
for (var i = 0; i < checkerArr.length; i++) {
checkerArr[i].onchange = function() {
if(this.checked){
sendbtn.disabled = false;
} else {
sendbtn.disabled = true;
}
}
}
I guess this code will help you
window.onload=function(){
var checkboxes = document.getElementsByClassName('checkbox')
var sendbtn = document.getElementById('sendNewSms');
var length=checkboxes.length;
for(var i=0;i<length;i++){
var box=checkboxes[i];
var isChecked=box.checked;
box.onchange=function(){
sendbtn.disabled=isChecked?true:false;
}
}
// when unchecked or checked, run the function
}
<input type="checkbox" id="check1" class="checkbox"/> Option1<br>
<input type="checkbox" id="check2" class="checkbox"/> Option2<br>
<input type="checkbox" id="check3" class="checkbox"/> Option3<br>
<input type="submit" name="sendNewSms" class="inputButton" disabled="disabled" id="sendNewSms" value=" Send " />
Few suggestions
1.Always id should be unique. HTML does not show any error, if you give multiple objects with the same id but when you try to get it by document.getelementbyid it always return the first one,because getelementbyid returns a single element
when there is such requirement, you should consider having a classname or searching through the element name because getelementsbyclassname/tag returns an array
Here in the markup i have added an extra class to query using getelementsbyclassname
To avoid adding extra class, you can also consider doing it by document.querySelectorAll
check the following snippet
window.onload=function(){
var checkboxes = document.querySelectorAll('input[type=checkbox]')
var sendbtn = document.getElementById('sendNewSms');
var length=checkboxes.length;
for(var i=0;i<length;i++){
var box=checkboxes[i];
var isChecked=box.checked;
box.onchange=function(){
sendbtn.disabled=isChecked?true:false;
}
}
// when unchecked or checked, run the function
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="checkbox" id="check1" /> Option1<br>
<input type="checkbox" id="check2" /> Option2<br>
<input type="checkbox" id="check3" /> Option3<br>
<input type="submit" name="sendNewSms" class="inputButton" disabled="disabled" id="sendNewSms" value=" Send " />
Hope this helps
Something like this would do. I'm sure you can do it with less code, but I am still a JavaScript beginner. :)
HTML
<input type="checkbox" class="checkme" data-id="checkMe1"/> Option1<br>
<input type="checkbox" class="checkme" data-id="checkMe2"/> Option2<br>
<input type="checkbox" class="checkme" data-id="checkMe3"/> Option3<br>
<input type="submit" name="sendNewSms" class="inputButton" disabled="disabled" id="sendNewSms" value=" Send " />
JavaScript
//keep the checkbox states, to reduce access to the DOM
var buttonStatus = {
checkMe1: false,
checkMe2: false,
checkMe1: false
};
//get the handles to the elements
var sendbtn = document.getElementById('sendNewSms');
var checkBoxes = document.querySelectorAll('.checkme');
//add event listeners
for(var i = 0; i < checkBoxes.length; i++) {
checkBoxes[i].addEventListener('change', function() {
buttonStatus[this.getAttribute('data-id')] = this.checked;
updateSendButton();
});
}
//check if the button needs to be enabled or disabled,
//depending on the state of other checkboxes
function updateSendButton() {
//check through all the keys in the buttonStatus object
for (var key in buttonStatus) {
if (buttonStatus.hasOwnProperty(key)) {
if (buttonStatus[key] === true) {
//if at least one of the checkboxes are checked
//enable the sendbtn
sendbtn.disabled = false;
return;
}
}
}
//disable the sendbtn otherwise
sendbtn.disabled = true;
}
var check_opt = document.getElementsByClassName('checkit');
console.log(check_opt);
var btn = document.getElementById('sendNewSms');
function detect() {
btn.disabled = true;
for (var index = 0; index < check_opt.length; ++index) {
console.log(index);
if (check_opt[index].checked == true) {
console.log(btn);
btn.disabled = false;
}
}
}
window.onload = function() {
for (var i = 0; i < check_opt.length; i++) {
check_opt[i].addEventListener('click', detect)
}
// when unchecked or checked, run the function
}
<input type="checkbox" id="check1" class="checkit" />Option1
<br>
<input type="checkbox" id="check2" class="checkit" />Option2
<br>
<input type="checkbox" id="check3" class="checkit" />Option3
<br>
<input type="submit" name="sendNewSms" class="inputButton" disabled="true" id="sendNewSms" value=" Send " />

inner html radio button array value getting over written in for loop

I have written this code which should simply display the user's selection based on radio button clicked, There are multiple groups of radio buttons in the one form
<form name="makePicks">
<label class="green">
<input type="radio" id="x" onclick="handleClick()" name="picks1" value="Chiefs"><span>Chiefs</span>
</label>
<label class="yellow">
<input type="radio" onclick="handleClick()" name="picks1" value="Hurricanes"><span>'Hurricanes'</span>
</label>
<label class="pink">
<input type="radio" name="picks1" value="draw" onclick="handleClick()"><span>Draw</span>
</label>
<br />
<label class="green">
<input type="radio" id="x" onclick="handleClick()" name="picks2" value="Lions"><span>Lions</span>
</label>
<label class="yellow">
<input type="radio" onclick="handleClick()" name="picks2" value="Stormers"><span>'Stormers'</span>
</label>
<label class="pink">
<input type="radio" name="picks2" value="draw" onclick="handleClick()"><span>Draw</span>
</label>
<br />
</form>
<div id="dispPicks">
</div>
function handleClick() {
// Get all the inputs.
var inputs = makePicks.elements;
var radios = [];
//Loop and find only the Radios
for (var i = 0; i < inputs.length; ++i) {
if (inputs[i].type == 'radio') {
radios.push(inputs[i]);
}
}
//var found = 1;
for (var i = 0; i < radios.length; i++) {
if (radios[i].checked) {
document.getElementById("dispPicks").innerHTML="YOU HAVE SELECTED "+radios[i].value
//found = 0;
//break;
}
}
//if (found == 1) {
//alert("Please Select Radio");
//}
//event.preventDefault(); // disable normal form submit behavior
return false;
}
My problem is
The value of the array radios[i].value gets over written as you can see in the image below
In this example cheifs and Stormers both needs to be displayed, since it was selected
If anyone can help me with correct implementation it would be very much appreciated
I created a fiddle at this link https://jsfiddle.net/taditdash/w8hpQ/
You can modify your JavaScript code like this:
function handleClick() {
// Get all the inputs.
var inputs = makePicks.elements;
var radios = [];
//Loop and find only the Radios
for (var i = 0; i < inputs.length; ++i) {
if (inputs[i].type == 'radio') {
radios.push(inputs[i]);
}
}
myradiovalue = "";
for (var i = 0; i < radios.length; i++) {
if (radios[i].checked) {
if (myradiovalue=="")
myradiovalue=radios[i].value
else
myradiovalue=myradiovalue+ ", " +radios[i].value
}
}
document.getElementById("dispPicks").innerHTML = "YOU HAVE SELECTED " + myradiovalue;
return false;
}

Count the number of checked checkboxes in HTML

So basically i want to count the number of checkboxes that are ticked. I get my code to the point where it counts them successfully, but I want to put in an alert that shows the number of checkboxes ticked, the code does this but doesn't show the total count, it increments the total every refresh. I just want to know how I can show a total count.
It should display the total when the radio button 'yes' is clicked.
<br />Apples
<input type="checkbox" name="fruit" />Oranges
<input type="checkbox" name="fruit" />Mango
<input type="checkbox" name="fruit" />
<br />Yes
<input type="radio" name="yesorno" id="yes" onchange="checkboxes()"
function checkboxes(){
var inputElems = document.getElementsByTagName("input"),
count = 0;
for (var i=0; i<inputElems.length; i++) {
if (inputElems[i].type === "checkbox" && inputElems[i].checked === true){
count++;
alert(count);
}
}}
This should do the trick:
alert(document.querySelectorAll('input[type="checkbox"]:checked').length);
try this using jquery
Method 1:
alert($('.checkbox_class_here :checked').size());
Method 2:
alert($('input[name=checkbox_name]').attr('checked'));
Method: 3
alert($(":checkbox:checked").length);
Try this code
<br />Apples
<input type="checkbox" name="fruit" checked/>Oranges
<input type="checkbox" name="fruit" />Mango
<input type="checkbox" name="fruit" />
<br />Yes
<input type="radio" name="yesorno" id="yes" onClick="checkboxes();" />
Javascript
function checkboxes()
{
var inputElems = document.getElementsByTagName("input"),
count = 0;
for (var i=0; i<inputElems.length; i++) {
if (inputElems[i].type == "checkbox" && inputElems[i].checked == true){
count++;
alert(count);
}
}
}
FIDDLE DEMO
Thanks to Marlon Bernardes for this.
alert(document.querySelectorAll('input[type="checkbox"]:checked').length);
If you have more than one form with different checkbox names in each, the above code will count all checkboxes in all forms.
To get over this, you can modify it to isolate by name.
var le = document.querySelectorAll('input[name="chkboxes[]"]:checked').length;
The initial code was very nearly right. the line
alert(count);
was in the wrong place. It should have come after the second closing brace like this:-
function checkboxes()
{
var inputElems = document.getElementsByTagName("input"),
count = 0;
for (var i=0; i<inputElems.length; i++) {
if (inputElems[i].type == "checkbox" && inputElems[i].checked == true){
count++;
}
}
alert(count);
}
In the wrong place it was giving you an alert message with every checked box.
var checkboxes = document.getElementsByName("fruit");
for(i = 0 ; i<checkboxes.length; i++)
{
if(checkboxes[i].checked==0){checkboxes.splice(i,1);}
}
alert("Number of checked checkboxes: "+checkboxes.length);
function checkboxes(){
var inputs = document.getElementsByTagName("input");
var inputObj;
var selectedCount = 0;
for(var count1 = 0;count1<inputs.length;count1++) {
inputObj = inputs[count1];
var type = inputObj.getAttribute("type");
if (type == 'checkbox' && inputObj.checked) {
selectedCount++;
}
}
alert(selectedCount);
}
<html>
<body>Fruits
<br />
<input type="checkbox" name="fruit" checked/>Oranges
<input type="checkbox" name="fruit" />Mango
<input type="checkbox" name="fruit" />Apple
<br />Yes
<input type="radio" name="yesorno" id="yes" onClick="checkboxes();"/>
</body>
</html>

Categories