Function triggers when checkbox is checked, but clears when unchecked - javascript

Here is a simple calculation that is run when a checkbox is checked:
function calculate() {
var guests = document.getElementById("guests").value;
var drinkRate = 2;
var drinkCost = drinkRate * guests;
//output
document.getElementById("drinkPrice").value = '$' +
parseFloat(drinkCost).toFixed(2);
};
Number of guests:
<input type="number" name="guests" id="guests" value="4"><br>
Drinks<input type="checkbox" name="drinks" id="A" onchange="calculate()"><output id="drinkPrice"></output><br>
How can the calculation be cleared (or hidden) when the check box is unchecked?
Thanks

You can use the checked property of checkbox to identify the checkbox is checked or unchecked. The demo with your Code as:
function calculate() {
if (document.getElementById("A").checked) {
var guests = document.getElementById("guests").value;
var drinkRate = 2;
var drinkCost = drinkRate * guests;
//output
document.getElementById("drinkPrice").value = '$' +
parseFloat(drinkCost).toFixed(2);
} else {
document.getElementById("drinkPrice").value = "";
}
};
Number of guests:
<input type="number" name="guests" id="guests" value="4">
<br>
Drinks:
<input type="checkbox" name="drinks" id="A" onchange="calculate()">
<output id="drinkPrice"></output><br>

I would highly suggest you do not use the onchange event, use the onclick instead, for compatibility reasons best explained by #T.J. Crowder on this question
Simply change the onchange="calculate(this)" inside the checkbox tag to:
<input type='checkbox' onclick='calculate(this);'>

Check the checkbox current state and reset the value if the state is false.
function calculate() {
var guests = document.getElementById("guests").value;
var drinkRate = 2;
var drinkCost = drinkRate * guests;
//output
document.getElementById("drinkPrice").value = '$' +
parseFloat(drinkCost).toFixed(2);
if(!document.getElementById('A').checked) {
document.getElementById("drinkPrice").value = ""
}
};
Number of guests:
<input type="number" name="guests" id="guests" value="4"><br>
Drinks<input type="checkbox" name="drinks" id="A" onchange="calculate()"><output id="drinkPrice"></output><br>

You have to check if the checkbox check value is true.
Try this.
function calculate() {
if (!document.getElementById("A").checked) {
document.getElementById("drinkPrice").value = "";
} else {
var guests = document.getElementById("guests").value;
var drinkRate = 2;
var drinkCost = drinkRate * guests;
document.getElementById("drinkPrice").value = '$' + parseFloat(drinkCost).toFixed(2);
}
};
Number of guests:
<input type="number" name="guests" id="guests" value="4"><br>
Drinks<input type="checkbox" name="drinks" id="A" onchange="calculate()"><output id="drinkPrice"></output><br>

Related

JavaScript array application

I'm trying to create a sample accounting system, the checkbox can be add to the total after it's checked and the input text is the amount of the money.
but my result keep getting zero, I can't figure it out.
Anyone can help me handle this problem?
I've test that the length of total_ary is 0, I think that is the mainly problem
function Totalamount() {
var input_cb = document.getElementsByName('cb');
var amount = [];
var total_ary = [];
var total = 0;
var price = [10, 20, 30];
var i = 0;
for (i = 0; i < input_cb.length; i++) {
if (input_cb[i].checked) {
amount.push(document.getElementsByName("amount").value); //get amounts of the products
} else {
amount.push(0); //If there is no input, add 0 to the array
}
}
for (i = 0; i < total_ary.length; i++) {
total_ary.push(parseInt(amount[i] * price[i])); // Add the products' total price to array
total += parseInt(total_ary[i]); //Counting the total money
}
document.getElementById("result").innerHTML = "$" + 0;
document.getElementById("result").innerHTML = "$" + total ;
}
<fieldset>
<input type="checkbox" name="cb" checked>$10:<input type="text" name="amount"><br>
<input type="checkbox" name="cb" checked>$20:<input type="text" name="amount"><br>
<input type="checkbox" name="cb" checked>$30:<input type="text" name="amount"><br>
</fieldset>
<button onclick="Totalamount()">Count</button>
<p>Total = <span id="result">
You do
document.getElementsByName("amount").value
but getElementsByName returns a collection, not an element.
You do
var total_ary = [];
// ... code that doesn't reference total_ary
for (i = 0; i < total_ary.length; i++) {
total_ary.push(parseInt(amount[i] * price[i])); // Add the products' total price to array
total += parseInt(total_ary[i]); //Counting the total money
}
But since the code in between doesn't reference total_ary, the total ends up being 0.
From a selected checkbox, you need to navigate to the associated input:
document.getElementsByName("amount")[i].value
since i is the cb index you're iterating over, the same i in the amount collection will refer to the input you need.
Or, more elegantly, just navigate to the next element in the DOM when a checkbox is checked, and take the number for each product's price from the DOM too. You can also select only the checked checkboxes immediately with a :checked selector, and attach the event listener using addEventListener (instead of an inline handler; inline handlers should be avoided)
document.querySelector('button').addEventListener('click', () => {
let total = 0;
for (const input of document.querySelectorAll('[name=cb]:checked')) {
const price = input.nextSibling.textContent.match(/\d+/)[0];
const amount = input.nextElementSibling.value;
total += price * amount;
}
document.getElementById("result").innerHTML = total + "元";
});
<fieldset>
<input type="checkbox" name="cb" checked>$10:<input><br>
<input type="checkbox" name="cb" checked>$20:<input><br>
<input type="checkbox" name="cb" checked>$30:<input><br>
</fieldset>
<button>Count</button>
<p>Total = <span id="result">
document.getElementsByName() returns a collection of elements. so calling value property will not work there as it does not have such property.
You can hold input elements with amount_inputs variable and iterate over it (in the example below by using spread syntax and Array.reduce())
And with Array.reduce() you can calculate the sum of the prices. There is no need for var amount = [] and var total_ary = [] variables.
Hope this helps
function Totalamount() {
var input_cb = document.getElementsByName('cb');
var amount_inputs = document.getElementsByName("amount")
var total = 0;
var price = [10, 20, 30];
total = [...input_cb].reduce((total, cb, i) => {
if(cb.checked){
total += (parseInt(amount_inputs[i].value) || 0) * price[i]
// ^^^^^^^^^ This is to avoid NaN multiplication
}
return total
},0);
document.getElementById("result").innerHTML = "$" + 0;
document.getElementById("result").innerHTML = total + "元";
}
<fieldset>
<input type="checkbox" name="cb" checked>$10:<input type="text" name="amount"><br>
<input type="checkbox" name="cb" checked>$20:<input type="text" name="amount"><br>
<input type="checkbox" name="cb" checked>$30:<input type="text" name="amount"><br>
</fieldset>
<button onclick="Totalamount()">Count</button>
<p>Total = <span id="result">
Use Index while retrieving the element from document.getElementsByName("amount");
Use for loop on amount array not on total_ary
function Totalamount() {
var input_cb = document.getElementsByName('cb');
var amount = [];
var total_ary = [];
var total = 0;
var price = [10, 20, 30];
var i = 0;
for (i = 0; i < input_cb.length; i++) {
if (input_cb[i].checked) {
amount.push(document.getElementsByName("amount")[i].value); //get amounts of the products
} else {
amount.push(0); //If there is no input, add 0 to the array
}
}
for (i = 0; i < amount.length; i++) {
total_ary.push(parseInt(amount[i] * price[i])); // Add the products' total price to array
total += isNaN(parseInt(total_ary[i])) ? 0 : parseInt(total_ary[i]); //Counting the total money
}
document.getElementById("result").innerHTML = "$" + 0;
document.getElementById("result").innerHTML = "$" + total ;
}
<fieldset>
<input type="checkbox" name="cb" checked>$10:<input type="text" name="amount"><br>
<input type="checkbox" name="cb" checked>$20:<input type="text" name="amount"><br>
<input type="checkbox" name="cb" checked>$30:<input type="text" name="amount"><br>
</fieldset>
<button onclick="Totalamount()">Count</button>
<p>Total = <span id="result">
You have made a few mistakes:
(1) If you want to keep all the checkboxes checked at initial stage
use checked="true" in place of checked
(2) getElementsByName("amount") returns an array, so you should use the index as well
(3) total_ary length is 0 initially.. therefore, you should run the loop with input_cb. (Here, you can do both the task with a single loop: refer code below)
Refer the code with corrections:
<!DOCTYPE html>
<html>
<head>Order sys
<script>
function Totalamount() {
var input_cb = document.getElementsByName('cb');
var amount = [];
var total = 0;
var price = [10,20,30];
var i=0;
for (i = 0; i < input_cb.length; i++) {
if (input_cb[i].checked){
amount.push(parseInt(document.getElementsByName("amount")[i].value)); //get amounts of the products
}
else{
amount.push(0); //If there is no input, add 0 to the array
}
total += parseInt(amount[i] * price[i]) //Counting the total money
}
document.getElementById("result").innerHTML = "$" + 0;
document.getElementById("result").innerHTML = total + "元";
}
</script>
</head>
<body>
<fieldset>
<input type = "checkbox" name="cb" checked="true">$10:<input type="text" id="amount_milk" name="amount" ><br>
<input type = "checkbox" name="cb" checked="true">$20:<input type="text" id="amount_soymlik" name="amount"><br>
<input type = "checkbox" name="cb" checked="true">$30:<input type="text" id="amount_blacktea" name="amount" ><br>
</fieldset>
<button onclick="Totalamount()">Count</button>
<p>Total = <span id="result">
</body>
</html>
You can refactor your code:
Fist use inputs of type number <input type="number" name="amount"> to accept only numbers from your end users
Then, you can work with indexed arrays like [...document.querySelectorAll('input[name="cb"]')] and loop only one time with Array.prototype.reduce() to get the total
Code example:
function Totalamount() {
const inputNumberArr = [...document.querySelectorAll('input[name="cb"]')]
const inputAmountArr = [...document.querySelectorAll('input[name="amount"]')]
const priceArr = [10, 20, 30]
const total = inputNumberArr.reduce((a, c, i) => {
const num = c.checked ? +inputAmountArr[i].value : 0
return a + num * priceArr[i]
}, 0)
document.getElementById('result').innerHTML = '$' + 0
document.getElementById('result').innerHTML = '$' + total
}
<fieldset>
<input type="checkbox" name="cb" checked> $10:
<input type="number" name="amount"><br>
<input type="checkbox" name="cb" checked> $20:
<input type="number" name="amount"><br>
<input type="checkbox" name="cb" checked> $30:
<input type="number" name="amount"><br>
</fieldset>
<button onclick="Totalamount()">Count</button>
<p>Total = <span id="result">
Is this what you are looking for?
Errors that I identified.
Making use of document.getElementsByName("amount").value instead of making the respective amount field you were making use of the global selector.
Trying to loop total_ary array instead of amount array.
function Totalamount() {
var input_cb = document.getElementsByName('cb');
var amountInput = document.getElementsByName('amount');
var amount = [];
var total_ary = [];
var total = 0;
var price = [10,20,30];
var i=0;
for (i = 0; i < input_cb.length; i++) {
if (input_cb[i].checked && amountInput[i].value){
amount.push(parseInt(amountInput[i].value)); //get amounts of the products
}
else{
amount.push(0); //If there is no input, add 0 to the array
}
}
for (i = 0; i < amount.length; i++) {
total_ary.push(parseInt(amount[i] * price[i])); // Add the products' total price to array
total += parseInt(total_ary[i]); //Counting the total money
}
document.getElementById("result").innerHTML = "$" + 0;
document.getElementById("result").innerHTML = total + "元";
}
<fieldset>
<input type = "checkbox" name="cb" checked>$10
<input type="text" id="amount_milk" name="amount" ><br>
<input type = "checkbox" name="cb" checked>$20
<input type="text" id="amount_soymlik" name="amount"><br>
<input type = "checkbox" name="cb" checked>$30
<input type="text" id="amount_blacktea" name="amount" ><br>
</fieldset>
<button onclick="Totalamount()">Count</button>
<p>Total = <span id="result">

get the sum of two checkbox on check

hy, my is that it doesn't work. i want on check to visualize the sum between the selected checkbox. for example if i check only the first, it shows me a value, for the other one another value; if i check both, the sum of the values.
thanks for the help
<div>
<input type="checkbox" id="checkvalnotset1" value="45" onClick="sumvalnotset()"> this is a checkbox that gain value when checked
<input type="checkbox" id="checkvalnotset2" value="20" onClick="sumvalnotset()"> this is a checkbox that gain value when checked
<p id="sumvalnotset">the value is 0</p>
<script>
function setvalue(x){
if(x.checked){
x.value = x.defaultValue;
} else {
x.classList.value = 0;
}
return x.value;
}
var a = setvalue(document.getElementById("checkvalnotset1"));
var b = setvalue(document.getElementById("checkvalnotset2"));
var p = document.getElementById("sumvalnotset");
function sumvalnotset(){
p.innerHTML = "the value is " + +a + +b
}
</script>
</div>
var sum = 0;
function sumvalnotset(event) {
if(event.checked) {
sum = sum + parseInt(event.value);
} else {
sum = sum > 0 ? sum - parseInt(event.value) : sum;
}
document.getElementById('sumvalnotset').innerText = 'the value is: '+ sum;
}
<div>
<input type="checkbox" id="checkvalnotset1" value="45" onClick="sumvalnotset(this)" onchange=""> this is a checkbox that gain value when checked
<input type="checkbox" id="checkvalnotset2" value="20" onClick="sumvalnotset(this)"> this is a checkbox that gain value when checked
<p id="sumvalnotset">
the value is: 0
</p>
</div>
You could rewrite your event handler has follows:
<div>
<input type="checkbox" id="checkvalnotset1" value="45" onClick="sumvalnotset()"> this is a checkbox that gain value when checked
<input type="checkbox" id="checkvalnotset2" value="20" onClick="sumvalnotset()"> this is a checkbox that gain value when checked
<p id="sumvalnotset">the value is 0</p>
<script>
function sumvalnotset() {
var chk1 = document.getElementById("checkvalnotset1");
var chk2 = document.getElementById("checkvalnotset2");
var val1 = chk1.checked ? Number(chk1.value):0;
var val2 = chk2.checked ? Number(chk2.value):0;
var p = document.getElementById("sumvalnotset");
p.innerHTML = "the value is " + (val1 + val2);
}
</script>
</div>

Get array textfield and calculate javascript

forexample, i have this code (results from a php script loop):
<input type="text" name="qtty[]" id="qtty[]" onFocus="startCalc();" onblur="stopCalc();">
<input type="hidden" name="price[]" id="price[]">
<input type="text" name="totalprice[]" id="totalprice[]">
And this for javascript:
function startCalc(){
interval = setInterval("calc()",500);
}
function calc(){
$('input[name="qtty[]"]').each(function(){
qtty = $(this).val();
});
$('input[name="price[]"]').each(function(){
price = $(this).val();
});
total = (qtty * 1) * (price * 1);
$('input[name="totalprice[]"]').val(total);
}
function stopCalc(){
clearInterval(interval);
}
The moment I enter the first input to the array, the program does not show anything. but at the time of the second array of data fed, TotalPrice will change both
Here, Example pict:
http://s7.postimg.org/memsupuh7/Capture1.png
http://s23.postimg.org/6rdfk2rzf/Capture.png
I think you are in the wrong way. This is more preferred variant:
<input type="text" name="qtty">
<input type="hidden" name="price" value="2">
<input type="text" name="totalprice">
<br>
<input type="text" name="qtty">
<input type="hidden" name="price" value="3">
<input type="text" name="totalprice">
and
$('input[name="qtty"]').keyup(function() {
var qtty = $(this).val();
var price = $(this).next().val();
var total = (qtty * 1) * (price * 1);
$(this).nextAll().eq(1).val(total);
});
fiddle
try this
Assign the default value initially
var qtty=0;
var price =0;
var interval ;
function startCalc(){
interval = setInterval(calc,500);
}
function calc(){
$('input[name="qtty[]"]').each(function(){
qtty = $(this).val();
});
$('input[name="price[]"]').each(function(){
price = $(this).val();
});
total = (qtty * 1) * (price * 1);
$('input[name="totalprice[]"]').val(total);
}
function stopCalc(){
clearInterval(interval);
}

Javascript checkbox values

I have this javascript code, that substracts from a total sum, a value when a checkbox is checked. In my case for each checkbox checked it substracts 20.
<script language="JavaScript">
function Calculate(){
var tag = window.document.getElementsByClassName("hsnb"), total = <? echo $total; ?>;
for (var i in tag){
total -= tag[i].checked && !isNaN(Number(20)) ? Number(20) : 0;
}
var cucu = + total.toFixed(2);
if(cucu < "20"){
alert("You dont have enough points!");
for(i = 1; document.getElementById("bifa" + i) !== null; i++) {
if (document.getElementById("bifa" + i).checked){
} else {
document.getElementById("bifa" + i).disabled = true;
}
}
}
window.document.getElementById("outputDiv").innerHTML = '<span style="font-size:20px;">You have: POINTS' + cucu + '</span>';
}​
</script>
I want to give each checkbox a certain value, let's say:
<input type="checkbox" id="check" name="check" value="10">
<input type="checkbox" id="check" name="check" value="20">
And if i check the first checkbox it should substract 10 and if i check the second checkbox substract 20. You know what i mean, substract the value for each checkbox. Can you help me with this?
Hi you should try using jQuery, something like
var sub = 0;
jQuery("input[name=check]:checked").each(function(index, element){
sub = sub + jQuery(element).val();
});
var total = yourNumber - sub;
I'haven't tested this snippet but it should work
Hope it helps
In plain javascript you can attach an event to each input an check the "checked" property each time the handler is invoked; if true then substract the input value from the total sum:
<input type="checkbox" id="check" name="check" value="10">
<input type="checkbox" id="check" name="check" value="20">
<script type="text/javascript">
window.onload = function(){
var aBox = document.getElementsByTagName("input"), iTotal = <? echo $total; ?>;
Array.prototype.forEach.call(aBox,function(oCheck, iIdx,aBox){
oCheck.onclick = function(){
if(this.checked){
iTotal = iTotal - this.value;
console.log(iTotal);
}
}
});
}
</script>

Trying to take which radio button is selected and when is put it through code is returns undefined

Hello I'm new to JavaScript and trying to get a radio button to be registered on variable and then have that variable return another var but it just keeps being returned undefined. If I'm just doing something overtly wrong please tell me.
The radio buttons
Fighter:<input type="radio" id="fig" value="1"/>
Cleric:<input type="radio" id="cleric" value="2"/>
Sorcerer:<input type="radio" id="wiz" value="3"/>
my js
var lvl
var bab
if (document.getElementById('fig').checked) {
var cass = document.getElementById('fig').value;
if (cass == 1){
bab = 1;
}
else if (cass == 2){
bab = 2;
}
else{
bab = 3;
}
}
function show(){
var txtOutput = document.getElementById("txtOutput");
txtOutput.value = bab;
}
And my final place its supposed to be submitting.
<input id="txtOutput">
</input>
Add change event listener for all radio inputs and on change of the input, set the value of the textbox.
Document.querySelectorAll Returns a list of the elements within the document that match the specified group of selectors.
Try this:
var elems = document.querySelectorAll('[name="name"]');
Array.prototype.forEach.call(elems, function(elem) {
elem.addEventListener('change', function() {
document.getElementById("txtOutput").value = this.value;
});
});
Fighter:
<input type="radio" id="fig" value="1" name='name' />Cleric:
<input type="radio" id="cleric" value="2" name='name' />Sorcerer:
<input type="radio" id="wiz" value="3" name='name' />
<br>
<input id="txtOutput">
I think this will give you clarity.
var lvl = "";
var bab = "";
function getValues() {
if (document.getElementById('fig').checked) {
bab = "1 : " + document.getElementById('fig').value + "\n";
}
if (document.getElementById('cleric').checked) {
bab += "2 : " + document.getElementById('cleric').value + "\n";
}
if((document.getElementById('wiz').checked)){
bab += "3 : " + document.getElementById('wiz').value;
}
show();
}
function show(){
var txtOutput = document.getElementById("txtOutput");
txtOutput.innerHTML = bab;
}
/* or you can call it when you click on it */
function consoleIt(obj) {
console.log(obj.id + " : " + obj.value);
}
Fighter : <input type="radio" onclick="consoleIt(this);" id="fig" value="1"/>
Cleric : <input type="radio" onclick="consoleIt(this);" id="cleric" value="2"/>
Sorcerer : <input type="radio" onclick="consoleIt(this);" id="wiz" value="3"/>
<button onclick="getValues();">Get Radio Data</button>
<textarea id="txtOutput"> </textarea>

Categories

Resources