JavaScript adding number variables together within different functions - javascript

In JavaScript I want to add two numeric variables: film_cost and delivery_cost and have them appear in a alert box. These variables are within two different functions.
function getcost()
{
var cost = document.getElementsByName("format");
var len = cost.length
for (i=0;i<len;i++)
{
if(cost[i].checked)
{
document.getElementById("data2").innerHTML = '£'+cost[i].value;
var film_cost = cost[i].value;
}
}
}
function add_delivery()
{
var delivery_cost = document.getElementsByName("delivery");
var len = delivery_cost.length
for (i=0;i<len;i++)
{
if(delivery_cost[i].checked)
{
var dvd_delivery = delivery_cost[i].value;
var total = dvd_delivery+film_cost;
alert(total);
}
}
}
HTML:
Delivery
<input type="radio" name="delivery"
onClick="add_delivery();" value="3.20">First Class<br/>
<input type="radio" name="delivery"
onClick="add_delivery();" value="4.20">Express Delivery<br/>
Film type:
<input type="radio" name="format" value="20"
onClick="getcost();">Blu-ray + UV Copy<br/>
<input type="radio" name="format" value="14.50"
onClick="getcost();">DVD + UV Copy<br/>
<input type="radio" name="format" value="30"
onClick="getcost();">Limited Edition DVD + UV Copy<br/>
<input type="radio" name="format" value="13"
onClick="getcost();">Download<br/>
How do I do it?

You need to gain access to the film_cost variable in the add_delivery() function.
I would recommend doing something like this:
function getcost()
{
var cost = document.getElementsByName("format");
var len = cost.length;
var film_cost = 0;
for (i=0;i<len;i++)
{
if(cost[i].checked)
{
document.getElementById("data2").innerHTML = '£'+cost[i].value;
film_cost = parseFloat(cost[i].value);
}
}
return film_cost;
}
function add_delivery()
{
var delivery_cost = document.getElementsByName("delivery");
var len = delivery_cost.length;
for (i=0;i<len;i++)
{
if(delivery_cost[i].checked)
{
var dvd_delivery = parseFloat(delivery_cost[i].value);
var total = dvd_delivery + getcost();
alert(total);
}
}
}
In this solution, the variable film_cost would default to 0, but will change if a box is checked. add_delivery() calls getcost() so the variables dvd_delivery and film_cost will add together into the variable total.
It would be helpful if we could see the html, but I think this will help you.
One final recommendation would be to normalize the way you name your functions. It would help you (and others) read your code if you named them:
getCost() and addDelivery()
or
get_cost() and add_delivery()
EDIT: Added parseFloat() to turn film_cost and dvd_delivery into floats so they can add together in the alert.

film_cost is not defined in the second function.

The scope of the variable film_cost is only inside the first function; therefore, when invoking the second function film_cost already "died".
An even simpler fix to the problem is simply:
var film_cost;
function getcost()
{
var cost = document.getElementsByName("format");
var len = cost.length
for (i=0;i<len;i++)
{
if(cost[i].checked)
{
document.getElementById("data2").innerHTML = '£'+cost[i].value;
film_cost = cost[i].value;
}
}
}
function add_delivery()
{
var delivery_cost = document.getElementsByName("delivery");
var len = delivery_cost.length
for (i=0;i<len;i++)
{
if(delivery_cost[i].checked)
{
var dvd_delivery = delivery_cost[i].value;
var total = dvd_delivery+film_cost;
alert(total);
}
}
}
I only changed the first line, and the if(cost[i].checked) body.
Hopefully it works as you'd hope!

Related

How can i change on click function every time i got an error

I want first click to make the getNumberBtn to be getNumberBtnn
and the second one to get it back to getNumberBtn function.
When I click, the function run but doesn't change the onclick property
var equation = 0;
function getNumberBtn() {
document.getElementById("apply").onclick = getNumberBtnn();
equation = equation + x;
}
function getNumberBtnn() {
document.getElementById("apply").onclick = getNumberBtn();
equation = equation + x;
}
<div>
<input type="number" id="number" min="1" max="1000">
<button id="apply" onclick=getNumberBtn()>Apply</button>
</div>
When you assign the function to onclick, you are actually calling the function and thus creating an infinite recursive.
You can just assign the function name to onclick -
var equation = 0;
function getNumberBtn() {
document.getElementById("apply").onclick = getNumberBtnn;
equation = equation + document.getElementById("number").value;
console.log('Called getNumberBtn');
}
function getNumberBtnn() {
document.getElementById("apply").onclick = getNumberBtn;
equation = equation + document.getElementById("number").value;
console.log('Called getNumberBtnn');
}
<div>
<input type="number" id="number" min="1" max="1000">
<button id="apply" onclick=getNumberBtn()>Apply</button>
</div>
But I would suggest you use DOM event registration instead using addEventListener and removeEventListener-
var equation = 0;
var apply = document.getElementById("apply");
apply.addEventListener('click', getNumberBtn);
function getNumberBtn() {
apply.removeEventListener('click', getNumberBtn);
apply.addEventListener('click', getNumberBtnn);
equation = equation + document.getElementById("number").value;
console.log('Called getNumberBtn');
}
function getNumberBtnn() {
apply.removeEventListener('click', getNumberBtnn);
apply.addEventListener('click', getNumberBtn);
equation = equation + document.getElementById("number").value;
console.log('Called getNumberBtnn');
}
<div>
<input type="number" id="number" min="1" max="1000">
<button id="apply">Apply</button>
</div>
You do not assign the event handler but the result of the function.
As I said in my comment, remove the () from the end of the function you assign.
Also you do not assign anything to x
However I suggest you do this instead:
Use eventListener
Use a function to decide which function to call
Have the list on functions in an object
Actually have different functions
let equation = 0;
const funcs = {
"btn": function(x) {
equation += x; // for example
console.log("btn", equation)
},
"btnn": function(x) {
equation *= x; // for example
console.log("btnn", equation)
}
}
document.getElementById("apply").addEventListener("click", function(e) {
const tgt = e.target;
const func = tgt.dataset.func
tgt.dataset.func = func === "btn" ? "btnn" : "btn"; // toggle the function
funcs[func](+document.getElementById("number").value); // call the chose function with a value
})
<div>
<input type="number" id="number" min="1" max="1000">
<button type="button" data-func="btn" id="apply">Apply</button>
</div>
Remove () from in front of function name while editing onclick property
function getNumberBtn() {
document.getElementById("apply").onclick = getNumberBtnn;
equation = equation + x;
}
function getNumberBtnn() {
document.getElementById("apply").onclick = getNumberBtn;
equation = equation + x;
}

Adding sum of array with pushed input values

I have pushed an input value to an empty array and converted it into a number. I am trying to add up the array and show the sum. But the whole array is shown and no addition has been done. I've included some of the code here but I'll also include the JS fiddle in case I forgot something important. I may be overthinking it as I have been looking at it for sometime.
JS Fiddle: https://jsfiddle.net/nzart/emruz0sb/4/
// HTML
<h1>Sugar Counter:</h1><p id="total">--</p>
<div class="box bot1">
<div class="twogrid mid">
<label for="amount">Amount of Sugar</label>
<input type="text" name="amount" id="amount">
</div>
</div>
//JS
var added = [];
//Get Data
var userInput = function(){
return parseFloat(document.getElementById('amount').value);
}
// Store Data
var newSugar = function(){
return added.push(userInput());
}
//Add total
function total() {
var sum = 0;
for (var i = 0; i < added.length; i++) {
sum += added[i];
}
document.getElementById('total').textContent = added;
}
This line is incorrect inside of function total():
document.getElementById('total').textContent = added;
Change to this:
document.getElementById('total').textContent = sum;
Here is an updated fiddle: https://jsfiddle.net/bqt1mws7/
You are displaying the array variable not the sum variable. Assign the sum variable to #total, not added variable.
document.getElementById('total').textContent = sum;
You need a button to perform the summation to update the total.
The Array.prototype.reduce function is a easy way to total values inside of a list.
values.reduce((runningTotal, currentValue) => runningTotal + currentValue, initialValue)
var valueList = [];
document.getElementById('btn-add').addEventListener('click', onAddClick);
function onAddClick(e) {
var value = getCurrentValue();
if (isNaN(value)) {
alert('Value is not a number!');
return;
}
valueList.push(value);
document.getElementById('total').textContent = getTotal();
}
function getCurrentValue() {
return parseFloat(document.getElementById('amount').value.trim());
}
function getTotal() {
return valueList.reduce((a, b) => a + b, 0); // Sum the values in the list
}
<h1>Sugar Counter:</h1>
<label>Total:</label>
<span id="total">--</span>
<div class="box bot1">
<div class="twogrid mid">
<label for="amount">Amount of Sugar</label>
<input type="text" name="amount" id="amount">
<input type="button" value="Add" id="btn-add" />
</div>
</div>
There is no problem in the addition process. If the array is valid, the total() function will work well. But at the last statement of total() function, you put added variable as output. But it should be the value of sum variable.
function total() {
var sum = 0;
for (var i = 0; i < added.length; i++) {
sum += added[i];
}
document.getElementById('total').textContent = sum;
}

Javascript - How to add results of two text boxes and display the result in a third?

I have two incrementally adding/subtracting values based on a button with onclick, as seen in below, and I attempted to have the outputs of these two boxes add into a third.
Javascript:
var i = 1;
function buttonClick() {
i++;
document.getElementById('inc').value = i;
}
function buttonClickA() {
i--;
document.getElementById('inc').value = i;
}
var w = 1;
function buttonClickC() {
w++;
document.getElementById('inc1').value = w;
}
function buttonClickD() {
w--;
document.getElementById('inc1').value = w;
}
function sum() {
var txtFirstNumberValue = document.getElementById('inc').value;
var txtSecondNumberValue = document.getElementById('inc1').value;
var result = parseInt(txtFirstNumberValue) + parseInt(txtSecondNumberValue);
if (!isNaN(result)) {
document.getElementById("tot").value = result;
}
}
And the HTML:
<button onclick="buttonClick()">Add</button>
<input type="text" id="inc" value="0">
<button onclick="buttonClickA()">Subtract</button>
<button onclick="buttonClickC()">Add</button>
<input type="text" id="inc1" value="0">
<button onclick="buttonClickD()">Subtract</button>
<input type="text" id="tot" />
It adds a third textbox and the first two work fine, but no new output in the third, not sure what I am doing wrong.
You haven't called the sum() function.
call the sum() function for every button click.

js crossing two function

I'm beginer in js, please help me.
I have two functions. First function sum all checked input ticket and view sum price, secondary function check discount code and takes into account the new price.
The problem is when I add a discount code and then will choose a ticket. Then it does not calculate the value.
https://jsfiddle.net/wznvfkm3/
$('.participantEventTicket').on('change', function() {
var totalPrice = 0.00;
$('.participantEventTicket:checked').each(function() {
totalPrice += parseFloat($(this).data('price'), 10);
});
$('.participantEventTicketSum').html(totalPrice.toFixed(2));
$('.participantEventTicketDiscountValueTotal').html(totalPrice);
});
$('.participantEventTicketDiscount').on('change', function() {
var code = ($(this).val());
var valueTotal = document.getElementById('participantEventTicketSum').innerHTML;
var value = 0;
var liste = [];
liste[0] = ['ABB'], -5]; liste[1] = ['BBC'], -10];
for (var i = 0, len = liste.length; i < len; i++) {
if (liste[i][0] === code) {
var value = liste[i][1];
}
}
var valueTotalS = parseInt(valueTotal) + parseFloat(value);
$('#participantEventTicketDiscountValue').html(value.toFixed(2));
$('#participantEventTicketDiscountValueTotal').html(valueTotalS);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
ticket 1
<input type="checkbox" name="participantEventTicket[]" value="5" class="participantEventTicket" />
<br/>ticket 2
<input type="checkbox" name="participantEventTicket[]" value="10" class="participantEventTicket" />
<br/>Sume tickets: <span class="participantEventTicketSum" id="participantEventTicketSum">0.00</span>
<br/>Discount coupon
<input type="text" id="participantEventTicketDiscount" class="participantEventTicketDiscount">
<br/>Discount value <span id="participantEventTicketDiscountValue" class="participantEventTicketDiscountValue">0.00</span>
<br/>Discount value sum <span id="participantEventTicketDiscountValueTotal" class="participantEventTicketDiscountValueTotal">0.00</span>
</form>
Slawotu,
Please check this fiddle
You had couple errors:
$('.participantEventTicket:checked').each(function () { totalPrice += parseFloat($(this).val(), 10);});
// you supposed to take $(this).val()
You didn't put calculation of total Price when you entered discount and changed you ticket:
$('.participantEventTicketDiscountValueTotal').html(totalPrice + value);
Forgot but brackets:
liste[0] = [['ABB'], -5];
liste[1] = [['BBC'], -10];
You compared 2 different objects using === instead use ==
if (liste[i][0] == code)
Declare val on top of the file, don't declare inside if statement.
var value = 0;

Don't run function if field empty

I'm new here, and very new to Javascript and programming concepts in general. Part of the form I'm working on simlpy needs to calculate the difference between two prices. I do know float numbers are screwy, so I have that part figured out. And it calculates, and inputs it into field 3. The only thing I can't seem to figure out is making it so that if either field 1 or 2 is empty, the function doesn't run. It should only run when both fields are filled. Here's my example code:
<input type="text" id="1"> </input><br/>
<input type="text" id="2"> </input><br/>
<input type="text" id="3"> </input><br/>
<br/><br/><br/>
<p id="test"></p>
<script src="http://code.jquery.com/jquery-1.11.2.min.js"></script>
<script>
function emptyCheck(){
if ($("#1") = ""){
$("#3").val("");
}
else if ($("#2") = ""){
$("#3").val("");
}
else{
rateDiff();
}
}
function rateDiff(){
var clientRate = $("#1").val() * 100;
var agentRate = $("#2").val() * 100;
var fareDiff = clientRate - agentRate;
var fareDiffDec = fareDiff / 100;
$("#3").val(fareDiffDec.toFixed(2));
}
$("#1").keyup(emptyCheck);
$("#2").keyup(emptyCheck);
</script>
I don't get what I'm doing wrong here. Can anyone point me in the right direction?
if ($("#1") = ""){
should be
if ($("#1").val() == ""){
same for $("#2") = ""
$("#1") is a jquery element, not the value.
Also you put = instead of ==
$("#1") = "")
Should be
$("#1").val() == "")
One = is used to assign a value, while two == is to do a comparison.
Just use the "falsey" of JavaScript and the values:
function emptyCheck(){
if (!$("#1").val() || !$("#2").val()){
$("#3").val("");
}
else{
rateDiff();
}
}
NOTE: you would be better parsing the numbers to handle alpha entry:
function emptyCheck() {
if (!parseFloat($("#1").val()) || !parseFloat($("#2").val())) {
$("#3").val("");
} else {
rateDiff();
}
}
function rateDiff() {
var clientRate = parseFloat($("#1").val()) * 100;
var agentRate = parseFloat($("#2").val()) * 100;
var fareDiff = clientRate - agentRate;
var fareDiffDec = fareDiff / 100;
$("#3").val(fareDiffDec.toFixed(2));
}
$("#1").keyup(emptyCheck);
$("#2").keyup(emptyCheck);

Categories