How Do I count the selected checkbox in AngularJS? - javascript

/**
* #Summary: checkAllConnectedUser function, to create album
* #param: index, productObj
* #return: callback(response)
* #Description:
*/
$scope.shardBuyerKeyIdArray = [];
$scope.countBuyer = 0;
$scope.checkAllSharedBuyer = function(isChecked) {
if (isChecked) {
if ($scope.selectAll) {
$scope.selectAll = false;
} else {
$scope.selectAll = true;
}
angular.forEach($scope.selectedSharedBuyerObjectList, function(selectedBuyer) {
selectedBuyer.select = $scope.selectAll;
//IF ID WILL BE EXIST IN THE ARRAY NOT PSUH THE KEYID
if ($scope.shardBuyerKeyIdArray.indexOf(selectedBuyer.userTypeDto.keyId) == -1) {
$scope.shardBuyerKeyIdArray.push(selectedBuyer.userTypeDto.keyId);
$scope.countBuyer++;
}
});
} else {
$scope.selectAll = false;
//USED FOR UNCHECK ALL THE DATA ONE- BY-ONE
angular.forEach($scope.selectedSharedBuyerObjectList, function(selectedBuyer) {
selectedBuyer.select = $scope.selectAll;
var index = $scope.shardBuyerKeyIdArray.indexOf(selectedBuyer.userTypeDto.keyId);
$scope.shardBuyerKeyIdArray.splice(index, 1);
$scope.countBuyer--;
});
}
}
<div class="checkbox w3-margin" ng-if="selectedSharedBuyerObjectList.length > 0">
<span class="w3-right" ng-if="countBuyer">
<h5>You are selecting {{countBuyer}} buyers!</h5>
</span>
<label>
<input type="checkbox" ng-model="selectAll" ng-click="checkAllSharedBuyer(selectAll)"/>Check All
</label>
</div>
<div id="sharedRow" class="checkbox" ng-repeat="selectedBuyer in cmnBuyer = (selectedSharedBuyerObjectList | filter : userSearchInProduct
| filter : filterUser)">
<label>
<input type="checkbox" ng-model="selectedBuyer.select"
ng-change="selectedSharedBuyer($index, selectedBuyer.select, selectedBuyer.userTypeDto.keyId)"/>
{{selectedBuyer.personName}}
</label>
</div>
I have two list in which i have to count the select all checkbox length as well as single checkbox count my problem if the user un-check the ALL checkbox Checkbox count will be return -- what's the problem in my code?

$(function(){
var count = 0;
$('#sharedRow ').find('input[type=checkbox]').on('change',function(){
$('#msg').text('You are selecting '+$('#sharedRow ').find('input[type=checkbox]:checked').length+' buyers!')
})
$('#chkAll').on('change', function () {
if ($(this).is(':checked')) {
$('#sharedRow ').find('input[type=checkbox]').prop('checked', true);
$('#msg').text('You are selecting '+$('#sharedRow ').find('input[type=checkbox]:checked').length+' buyers!')
}
else {
$('#sharedRow ').find('input[type=checkbox]').prop('checked', false);
$('#msg').text('You are selecting '+$('#sharedRow ').find('input[type=checkbox]:checked').length+' buyers!')
}
});
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="checkbox w3-margin">
<span class="w3-right">
<h5 id="msg" >You are selecting 0 buyers!</h5>
</span>
<label>
<input id="chkAll" type="checkbox" />Check All
</label>
</div>
<div id="sharedRow" class="checkbox">
<label>
<input type="checkbox" value="1 Buyers" />1 Buyers
</label>
<label>
<input type="checkbox" value="2 Buyers" />2 Buyers
</label>
<label>
<input type="checkbox" value="3 Buyers" />3 Buyers
</label>
<label>
<input type="checkbox" value="4 Buyers" />4 Buyers
</label>
<label>
<input type="checkbox" value="5 Buyers" />5 Buyers
</label>
<label>
<input type="checkbox" value="6 Buyers" />6 Buyers
</label>
<label>
<input type="checkbox" value="7 Buyers" />7 Buyers
</label>
<label>
<input type="checkbox" value="8 Buyers" />8 Buyers
</label>
</div>
try this one. is it ok? if not then tell me what's wrong.

if you have a group of checkbox then you can find all selected checkbox.
$('div').find('input[type=checkbox]:checked').length;

If you only need the number
var count = $scope.selectedSharedBuyerObjectList.reduce(function(sum, item) {
return (item.select) ? sum + 1 : sum;
}, 0);
If you need the filtered array
var selected = $scope.selectedSharedBuyerObjectList.filter(function(item) {
return item.select;
});
var count = selected.length;
Or do it using plain old loop
var count = 0;
for (i = 0; i < $scope.selectedSharedBuyerObjectList.length; i++) {
if ($scope.selectedSharedBuyerObjectList.select) count++;
}

Related

how to fix javascript

when the checkbox is checked by the user, I want to push the value(the numerical value are in the JS) for the checked box in an array, get the sum and display the total calories in the alert message.
here's my code so far:
var rice = 204;
var bread = 140;
var chicken = 147;
var beef = 282;
var carrots = 150;
var beans = 70;
function myFunction() {
var rice = document.getElementById("rice");
var bread = document.getElementById("bread");
var chicken = document.getElementById("chicken");
var beef = document.getElementById("beef");
var carrots = document.getElementById("carrots");
var beans = document.getElementById("beans");
const food = [];
if (rice.checked == true) {
food.push(window.rice);
} else if (bread.checked == true) {
food.push(window.bread);
} else if (chicken.checked == true) {
food.push(window.chicken);
} else if (beef.checked == true) {
food.push(window.beef);
} else if (carrots.checked == true) {
food.push(window.carrots);
} else if (beans.checked == true) {
food.push(window.beans);
}
let sum = food.reduce(function(a, b) {
return a + b;
}, 0);
console.log(sum); /*sum of array not working */
console.log(food);
}
myFunction();
<form>
<h2>Meal Plan</h2>
<h3>Dietary restrictions:</h3>
<input type="radio" name="diet" id="none" value="none" required>
<label for="none">None</label>
<br/><input type="radio" name="diet" id="vegetarian" value="vegetarian" required>
<label for="vegetarian">Vegetarian</label>
<br/><input type="radio" name="diet" id="lowcarb" value="lowcarb" required>
<label for="lowcarb">Low Carb</label>
<br />
<h3>Food items:</h3>
<input type="checkbox" name="Rice" id="rice" value="rice">
<label for="rice">Rice</label>
<br /><input type="checkbox" name="Beef" id="beef" value="beef">
<label for="beef">Beef</label>
<br /><input type="checkbox" name="Bread" id="bread" value="bread">
<label for="bread">Bread</label>
<br /><input type="checkbox" name="Beans" id="beans" value="beans">
<label for="beans">Beans</label>
<br /><input type="checkbox" name="Chicken" id="chicken" value="chicken">
<label for="chicken">Chicken</label>
<br /><input type="checkbox" name="Carrots" id="carrots" value="carrots">
<label for="carrots">Carrots</label>
<br /><br /><input type="submit" onclick="myFunction()" />
</form>
<script src="try.js"></script>
the values is not appending in the array when i check multuple boxes. it only appends the first box that i checked and doesn't include the next boxes. i cant get the sum, how can i fix that?
You can do this way
document.querySelector('form').addEventListener('click', e => {
if (e.target.matches('input[type="radio"]')) {
const checked = document.querySelector('#vegetarian').checked;
document.querySelectorAll('.meat').forEach(chk => {
chk.disabled = checked;
chk.checked = false;
});
}
});
const calories = {
rice: 204,
bread: 140,
chicken: 147,
beef: 282,
carrots: 150,
beans: 70
};
function myFunction() {
const food = [];
const veg = [];
let sum = 0;
document.querySelectorAll('input[type="checkbox"]').forEach(chk => {
if (chk.checked) {
food.push(chk.value);
if (chk.classList.contains('veg')) {
veg.push(chk.value);
}
sum += (calories[chk.value] || 0);
}
});
console.log(sum); /*sum of array not working */
alert(food);
if (veg.length < 2) {
alert('two vegs are recommendeded');
}
}
<!DOCTYPE html>
<html>
<head>
<title>Meal Plan</title>
</head>
<body>
<form onsubmit="return false;">
<h2>Meal Plan</h2>
<h3>Dietary restrictions:</h3>
<input type="radio" name="diet" id="none" value="none" required>
<label for="none">None</label>
<br/><input type="radio" name="diet" id="vegetarian" value="vegetarian" required>
<label for="vegetarian">Vegetarian</label>
<br/><input type="radio" name="diet" id="lowcarb" value="lowcarb" required>
<label for="lowcarb">Low Carb</label>
<br />
<h3>Food items:</h3>
<input type="checkbox" name="Rice" id="rice" value="rice">
<label for="rice">Rice</label>
<br /><input type="checkbox" name="Beef" class="meat" id="beef" value="beef">
<label for="beef">Beef</label>
<br /><input type="checkbox" name="Bread" id="bread" value="bread">
<label for="bread">Bread</label>
<br /><input type="checkbox" name="Beans" class="veg" id="beans" value="beans">
<label for="beans">Beans</label>
<br /><input type="checkbox" name="Chicken" class="meat" id="chicken" value="chicken">
<label for="chicken">Chicken</label>
<br /><input type="checkbox" name="Carrots" class="veg" id="carrots" value="carrots">
<label for="carrots">Carrots</label>
<br /><br /><input type="submit" onclick="myFunction()" />
</form>
</body>
</html>
Your existing if ... else if ... block got problem, it won't run the rest of else if once a condition is true.
do that this way ... (less code and more readability)
const
myForm = document.forms['my-form']
, calories =
{ rice : 204
, bread : 140
, chicken : 147
, beef : 282
, carrots : 150
, beans : 70
}
, NotVegetarianFood = ['beef', 'chicken' ]
;
myForm.oninput = e =>
{
if ( e.target.name === 'diet' )
{
let isVegetarian = (myForm.diet.value === 'vegetarian')
NotVegetarianFood.forEach( food =>
{
myForm[food].disabled = isVegetarian
if (isVegetarian)
myForm[food].checked = false
})
}
}
myForm.onsubmit = e =>
{
e.preventDefault()
let
sum = 0
, vegetables = 0
, formValues =
Array
.from(new FormData(myForm).entries() )
.reduce((res,[food,_])=>
{
if (!!calories[food])
{
vegetables += NotVegetarianFood.includes(food) ? 0 : 1
sum += calories[food]
res.push (food)
}
return res
},[])
myForm.message.textContent = (vegetables > 2)
? ''
: '2 vegetables options are recommended for a healthy meal regardless of the dietary restrictions.'
console.clear()
console.log( JSON.stringify( formValues), '\n-- calories sum =', sum )
}
fieldset {
width : 16em;
margin-bottom : .7em;
}
legend {
font-weight : bold;
}
label {
display : block;
margin-top : .4em;
}
<form name="my-form">
<h3>Meal Plan</h3>
<fieldset>
<legend>Dietary restrictions:</legend>
<label> <input type="radio" name="diet" value="none" checked > None </label>
<label> <input type="radio" name="diet" value="vegetarian" > vegetarian </label>
<label> <input type="radio" name="diet" value="lowcarb" > Low Carb </label>
</fieldset>
<fieldset>
<legend>Food items:</legend>
<label> <input type="checkbox" name="rice" > Rice </label>
<label> <input type="checkbox" name="beef" > Beef </label>
<label> <input type="checkbox" name="bread" > Bread </label>
<label> <input type="checkbox" name="beans" > Beans </label>
<label> <input type="checkbox" name="chicken" > Chicken </label>
<label> <input type="checkbox" name="carrots" > Carrots </label>
</fieldset>
<button type="submit">submit</button>
<output name="message"></output>
</form>

Passing arrays through checkbox input values?

I am trying to get the intersection of two arrays when the user selects them but I don't know how to pass an entire array through an input value.
Here is my script:
var checkedValue = document.querySelector('.leaflet-control-layers-selector:checked').value;
result = _.intersection(checkedValue);
console.log(checkedValue);
document.getElementById("AllMuseums").value = AllMuseums;
document.getElementById("MPaid").value = MPaid;
document.getElementById("MFree").value = MFree;
document.getElementById("MResto").value = MResto;
Here are my inputs:
<label>
<div><input type="checkbox" class="leaflet-control-layers-selector" id="AllMuseums" checked><span>All Museums</span></div>
</label>
<label>
<div><input type="checkbox" class="leaflet-control-layers-selector" id="MPaid" value="MPaid"><span id="icons1">Paid Admission</span></div>
</label>
<label>
<div><input type="checkbox" class="leaflet-control-layers-selector" id="MFree" value="MFree"><span id="icons2">Free Admission</span></div>
</label>
<label>
<div><input type="checkbox" class="leaflet-control-layers-selector" id="MResto" value="MResto"><span id="icons3">Restaurants</span></div>
</label>
And here are my arrays:
var AllMuseums=[Naturhistoriska,Junibacken,ArkDes,Fjarilshuset,Tekniska,Polismuseet,Skansen,Bergrummet,Vikingaliv,Vasa,Nordiska,Nobel,Moderna],
MPaid=[Junibacken,Fjarilshuset,Tekniska,Polismuseet,Skansen,Bergrummet,Vikingaliv,Vasa,Nordiska,Nobel],
MFree=[Naturhistoriska,ArkDes,Moderna],
MResto=[Naturhistoriska,Junibacken,ArkDes,Fjarilshuset,Tekniska,Skansen,Bergrummet,Vikingaliv,Vasa,Nordiska,Nobel,Moderna],
So there is a solution : https://jsfiddle.net/ajxeyqo4
inputs :
first input tag add value
<label>
<div><input type="checkbox" class="leaflet-control-layers-selector" id="AllMuseums" value="AllMuseums" checked><span>All Museums</span></div>
</label>
<label>
<div><input type="checkbox" class="leaflet-control-layers-selector" id="MPaid" value="MPaid"><span id="icons1">Paid Admission</span></div>
</label>
<label>
<div><input type="checkbox" class="leaflet-control-layers-selector" id="MFree" value="MFree"><span id="icons2">Free Admission</span></div>
</label>
<label>
<div><input type="checkbox" class="leaflet-control-layers-selector" id="MResto" value="MResto"><span id="icons3">Restaurants</span></div>
</label>
<button onclick='test()'>
test
</button>
And your scripts :
function test(){
var AllMuseums=['Naturhistoriska','Junibacken','ArkDes','Fjarilshuset','Tekniska','Polismuseet','Skansen','Bergrummet','Vikingaliv','Vasa','Nordiska','Nobel','Moderna'],
MPaid=['Junibacken','Fjarilshuset','Tekniska','Polismuseet','Skansen','Bergrummet','Vikingaliv','Vasa','Nordiska','Nobel'],
MFree=['Naturhistoriska','ArkDes','Moderna'],
MResto=['Naturhistoriska','Junibacken','ArkDes','Fjarilshuset','Tekniska','Skansen','Bergrummet','Vikingaliv','Vasa','Nordiska','Nobel','Moderna'];
var checkedValue = document.querySelectorAll('.leaflet-control-layers-selector:checked');
var a =[]
_.map(checkedValue, function(value) {
a.push(eval(value.value));
});
var result = _.intersection(...a);
console.log(JSON.stringify(result))
}

Textbox value not being multiplied when checkbox selected (HTML & Javascript/JQuery)

My code updates the CPC textbox when options are selected, but when an agency discount is selected (i.e. the 10% checkbox), it successfully lowers the CPC textbox value by 10% but does not do the same for the Total Cost textbox.
The Total Cost textbox value should be the (CPC textbox value * number of clicks textbox) * percentdiscount multiplier
Can anyone see where I'm going wrong? I'll be happy to clarify further if I haven't explained this very well!
HTML:
<div class="runningtotal">
Running CPC Total (in £): <input id="sum" type="text" readonly="true" value="0.00" data-total="0" />
Total Cost (in £): <input id="totalcost" type="text" readonly="true" value="0 (until clicks specified)" data-total="0" />
</div>
<div class="black_whitelisting">
<h1>4. Blacklist/Whitelist?</h1>
<input type="checkbox" class="blacklist" name="blacklist" value="0.20" id="blacklist_checkbox" onclick="BlacklistFunction()">Blacklist required<br>
<input type="checkbox" class="whitelist" name="whitelist" value="0.30" id="whitelist_checkbox">Whitelist required<br>
</div>
<div class="selecttier">
<h1>5. Number of Clicks</h1>
<input id="numberofclickstextbox" type="text" value="0.00" data-total="0" oninput="calculatetier()" />
</div>
<div class="agencydiscount">
<h1>6. Agency Discount</h1>
<label>
<input type="radio" name="percentdiscount" value="1" checked>
None
</label>
<label>
<input type="radio" name="percentdiscount" id="10percent" value="0.9" onclick="calculatetotalcost10()" >
10% Discount
</label>
<label>
<input type="radio" name="percentdiscount" id="15percent" value="0.85" onclick="calculatetier15()" >
15% Discount
</label>
</div>
Javascript:
jQuery(function($) {
$('input[name="percentdiscount"]').on('change', function() {
applyDiscount();
});
$('input[type=checkbox]').click(function() {
let sum = 0;
$('input[type=checkbox]:checked').each(function() {
sum += parseFloat($(this).val());
});
$('#sum').val(sum.toFixed(2)).data('total', sum);
applyDiscount();
});
function applyDiscount() {
var pc = parseFloat($('input[name="percentdiscount"]:checked').val());
$('#sum').val(function() {
return ($(this).data('total') * pc).toFixed(2);
});
}
});
//to work out total cost
function calculatetier() {
var myBox5 = document.getElementById('numberofclickstextbox').value;
var myBox6 = document.getElementById('sum').value;
var result = document.getElementById('totalcost');
var myResult = myBox5 * myBox6;
result.value = myResult.toFixed(2);
}
Looks like you are calculatetier function isn't being called during the change of discount.
Working Demo: https://codepen.io/punith/pen/gOpaVxr?editors=1010
HTML code
<div class="runningtotal">
Running CPC Total (in £): <input id="sum" type="text" readonly="true" value="0.00" data-total="0" />
Total Cost (in £): <input id="totalcost" type="text" readonly="true" value="0 (until clicks specified)" data-total="0" />
</div>
<div class="black_whitelisting">
<h1>4. Blacklist/Whitelist?</h1>
<input type="checkbox" class="blacklist" name="blacklist" value="0.20" id="blacklist_checkbox" >Blacklist required<br>
<input type="checkbox" class="whitelist" name="whitelist" value="0.30" id="whitelist_checkbox">Whitelist required<br>
</div>
<div class="selecttier">
<h1>5. Number of Clicks</h1>
<input id="numberofclickstextbox" type="text" value="0.00" data-total="0" oninput="calculatetier()" />
</div>
<div class="agencydiscount">
<h1>6. Agency Discount</h1>
<label>
<input type="radio" name="percentdiscount" value="1" checked>
None
</label>
<label>
<input type="radio" name="percentdiscount" id="10percent" value="0.9" >
10% Discount
</label>
<label>
<input type="radio" name="percentdiscount" id="15percent" value="0.85" >
15% Discount
</label>
</div>
JS Code
function calculatetier() {
var myBox5 = document.getElementById('numberofclickstextbox').value;
var myBox6 = document.getElementById('sum').value;
var result = document.getElementById('totalcost');
if(myBox6=="0.00"){
myBox6 =1;
}
console.log(myBox6)
var myResult = myBox5 * myBox6;
result.value = myResult.toFixed(2);
}
jQuery(function($) {
$('input[name="percentdiscount"]').on('change', function() {
applyDiscount();
});
$('input[type=checkbox]').click(function() {
let sum = 0;
$('input[type=checkbox]:checked').each(function() {
sum += parseFloat($(this).val());
});
$('#sum').val(sum.toFixed(2)).data('total', sum);
applyDiscount();
});
//to work out total cost
function applyDiscount() {
var pc = parseFloat($('input[name="percentdiscount"]:checked').val());
$('#sum').val(function() {
return ($(this).data('total') * pc).toFixed(2);
});
calculatetier()
}
});
try to use onchange event instead I guess the event you are binding is not correct
<input id="numberofclickstextbox" type="text" value="0.00" data-total="0" onchange="calculatetier()" />

Validation for dynamic radio button,checkbox and text area

I have developed one page,which is contains several questions and answer...there are three types of answer radio button,checkbox and text area... i have to validate these dynamically created questions using javascript...
based on the question type i am getting answer options from database whether it may be a radio button or checkbox or text area...
<input type="radio" id="radio" name="21" value="59"/>
<input type="radio" id="radio" name="22" value="60"/>
<input type="radio" id="radio" name="23" value="61"/>
like same as checkbox and text area....
//try 1
var form = document.getElementById('form1');
var inputs = form.getElementsByTagName('INPUT');
for (var i = 0; i < inputs.length; ++i) {
if (inputs[i].type.toLowerCase == 'radio' && !inputs[i].checked)
return false;
}
return true;
//try 2
var rv = document.getElementsByName("reservation_in");
var ci = -1;
for(var ikj=0; ikj < rv.length; ikj++){
if(rv[ikj].checked) {
ci = ikj;
}
}
if (ci == -1) {
document.getElementById('err_reservation_for').innerHTML="";
document.getElementById('err_reservation_for').innerHTML=
'Please let us know
//Reservation for Inside or Patio.';
return false;
}
//try 3
var radios = document.getElementById('radio');
var formValid = false;
var i = 0;
while (!formValid && i < radios.length) {
if (radios[i].checked)
formValid = true;
i++;
}
if (!formValid)
//document.getElementById('radio_error').innerHTML="";
//document.getElementById('radio_error').innerHTML=
'Please select one answer.';
alert("Please select the answer");
return formValid;
I have some sample code which may help you to understand more.
HTML Code:
<div id="que1" class="que">
xyz is not abc? <br />
<div class="ans">
<input type="radio" name="radioGroup1" id="radio1" />One
<input type="radio" name="radioGroup1" id="radio2" />Two
<input type="checkbox" name="check" id="check1" />Three <br/>
<textarea id="textarea-1"></textarea>
</div>
</div><br />
<div id="que2" class="que">
xyz is not abc? <br />
<div class="ans">
<input type="radio" name="radioGroup2" id="radio3" />One
<input type="radio" name="radioGroup2" id="radio3" />Two
<input type="checkbox" name="check" id="check2" />Three <br />
<textarea id="textarea-2"></textarea>
</div>
</div>
JS Code:
var questions=document.getElementsByClassName("que");
for(var i=0;i<questions.length;i++){
var inputs=questions[i].getElementsByTagName("input");
for(var j=0;j<inputs.length;j++){
if(inputs[j].type=="radio"){
alert("question ID:- "+ questions[i].id+ " radio");
}
if(inputs[j].type=="checkbox"){
alert("question ID:- "+ questions[i].id+ " checkbox");
}
}
var textarea=questions[i].getElementsByTagName("textarea");
for(var k=0;k<textarea.length;k++){
alert("question ID:- "+ questions[i].id+ " Textarea");
}
}
Click here check this fiddle
Radio button validation:
Html:
<form>
<input type="radio" id="21" name="radio" value="59"/>
<input type="radio" id="22" name="radio" value="60"/>
<input type="radio" id="23" name="radio" value="61"/>
</form>
Javascript:
if ( ( form.radio[0].checked == false ) && ( form.radio[1].checked == false ) && ( form.radio[2].checked == false ) ) { alert ( "Please choose one radio button" ); return false; }
If there are many input box then use each..that will iterate just like for loop..
var iz_checked = false;
var is_blank = false;
var is_choose = false;
$('button').on('click', function() {
iz_checked = false;
is_blank = false;
is_choose = false;
$('input[type="radio"]').each(function() {
if ($('input[type="radio"]').is(':checked') == true) {
iz_checked = false;
} else {
iz_checked = true;
}
if ($('textarea')[0].value == "") {
is_blank = true;
}
});
$('input[type="checkbox"]').each(function() {
if ($('input[type="checkbox"]').is(':checked') == true) {
is_choose = false;
} else {
is_choose = true;
}
});
if (is_choose || iz_checked || is_blank) {
alert("Validation err");
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
<input type="radio" id="21" value="59" />a
<input type="radio" id="22" value="60" />q
<input type="radio" id="23" value="61" />w
<input type="radio" id="1" value="59" />e
<input type="radio" id="2" value="60" />r
<input type="radio" id="3" value="61" />t
<input type="radio" id="29" value="59" />y
<input type="radio" id="80" value="60" />u
<input type="radio" id="7" value="61" />i
<input type="radio" id="8" value="59" />o
<input type="radio" id="0" value="60" />p
<input type="radio" id="1" value="61" />l
</form>
<textarea cols="10" rows="10"></textarea>
<br/>
<input type="checkbox" value="Apples">f
<input type="checkbox" value="Apples">d
<input type="checkbox" value="Apples">s
<input type="checkbox" value="Apples">a
<br/>
<button>
Validate
</button>

javascript adding select and checkbox values/// getting negative numbers

I need to be able to have the user pick a billing term from a select drop down and then choose checkboxes to add to the total. It seems to work relatively well on JSFIDDLE however on my site, there are some cases where selecting all the checkboxes and then resetting the total to 0 by selecting 'Choose billing term' then unchecking all the options will result in negative numbers. Does anyone have any suggestions? Even checking and unchecking options will start to get negative numbers.
HTML:
<div class="payment-term">
<label>Billing period:</label>
<select id="billing-price" name="billing-term" class="selectpicker">
<option value="0">Choose billing term</option>
<option value="300">12 Months: $300/mo. (Save 20%)</option>
<option value="350">1 Month: $350/mo.</option>
</select><br><br>
<label>Extra Features ($50/month): </label>
</div>
<section id="extra-features">
<div class="span3">
<label class="checkbox" for="Checkbox1">
<input type="checkbox" class="sum" value="50" data-toggle="checkbox"> Instagram
</label>
<label class="checkbox">
<input type="checkbox" class="sum" value="50" data-toggle="checkbox"> Review site monitoring
</label>
<label class="checkbox">
<input type="checkbox" class="sum" value="50" data-toggle="checkbox"> Google+
</label>
<label class="checkbox">
<input type="checkbox" class="sum" value="50" data-toggle="checkbox"> LinkedIn
</label>
</div>
<div class="span3">
<label class="checkbox">
<input type="checkbox" class="sum" value="50" data-toggle="checkbox"> Pinterest
</label>
<label class="checkbox">
<input type="checkbox" class="sum" value="50" data-toggle="checkbox"> FourSquare
</label>
<label class="checkbox">
<input type="checkbox" class="sum" value="50" data-toggle="checkbox"> Tumblr
</label>
<label class="checkbox">
<input type="checkbox" class="sum" value="50" data-toggle="checkbox"> Advertising
</label>
</div>
</section>
<div class="card-charge-info">
Your card will be charged $<span id="payment-total">0</span> now, and your subscription will bill $<span id="payment-rebill">0</span> every month thereafter. You can cancel or change plans anytime.
</div>
My javascript:
var select = document.getElementById('billing-price');
select.addEventListener('change', updatePrice, false);
var price = 0;
var additional = 0;
function updatePrice(e) {
price = parseFloat(select.value);
document.getElementById('payment-total').innerText = price + additional;
if (price == select.options[2].value){
document.getElementById('payment-rebill').innerText = 0 + additional;
} else {
document.getElementById('payment-rebill').innerText = price + additional;
}
}
var inputs = document.getElementsByClassName('sum'),
total = document.getElementById('payment-total');
total2 = document.getElementById('payment-rebill');
for (var i=0; i < inputs.length; i++) {
inputs[i].onchange = function() {
var add = this.value * (this.checked ? 1 : -1);
additional += add
total.innerHTML = price + additional
total2.innerHTML = price + additional
}
}
Working jsfiddle: http://jsfiddle.net/uZbee/2/
My site (not working correctly): http://thesomii.com/getstarted/basic/
I am using a javascript file for my checkboxes to give them a better appearance. I fear it maybe effecting my javascript code for the sum of checked boxes.
The negative value is caused by the input is not checked, so the this.checked in this line
var add = this.value * (this.checked ? 1 : -1);
is always false, resulting the added value is negative.
Change this.checked to this.parentNode.className.split(" ").indexOf("checked") > -1 may help.
for (var i=0; i < inputs.length; i++) {
inputs[i].onchange = function() {
var add = this.value * (this.parentNode.className.split(" ").indexOf("checked") > -1 ? 1 : -1);
additional += add
total.innerHTML = price + additional
total2.innerHTML = price + additional
}
}

Categories

Resources