Iterate through several ng-model - javascript

i had a set of ng-model elements and and want to sum all the values and display it. My set looks like these
<div ng-app>
<div ng-controller="SumApp" >
<input ng-model='val1' type='number' ng-change='calculate()' ng-init='val1=0'/>
<input ng-model='val2' type='number' ng-change='calculate()' ng-init='val2=0'/>
<input ng-model='val3' type='number' ng-change='calculate()' ng-init='val3=0'/>
<input ng-model='val4' type='number' ng-change='calculate()' ng-init='val4=0'/>
<div>{{sum}}</div>
</div>
</div>
And my controller looks like these
<script type="text/javascript">
function SumApp($scope) {
$scope.sum = 0;
$scope.calculate = function() {
$scope.sum = $scope.val1+$scope.val2+$scope.val3+$scope.val4
};
}
</script>
So like the html for the models is generate dynamically
The question is if there is any way that can i iterate through a set of elements ng-model without using any list in the controller definition itself ?

Knowing the exact number of inputs at any time you can easily use a loop to sum them up:
$scope.sum = 0;
$scope.numInputs = 5;
$scope.calculate = function() {
var i;
$scope.sum = 0;
for(i = 0; i < $scope.numInputs; i++) {
$scope.sum += parseInt($scope['val' + i], 10);
}
};

Related

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;
}

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;

How do I return a value from a function in JavaScript to a textbox in HTML

This is my HTML code:
<head>
</head>
<body>
LIMIT<input id='limit' name='' value='' class=''>
<button id='go' class=''>GO</button>
TOTAL<input id='total' name='' value='' class=''>
<script src='js/limitfor.js'></script>
</body>
And this is my JavaScript:
document.getElementById('go').onclick = function () {
var limit = document.getElementById('limit').value;
limit = parseFloat(limit);
total = 0;
for (i=0; i<=limit ;i++) {
total = total + i;
};
};
If I alert the total, I can see that the function works, but I need the total to be in the textbox rather than in a pop up alert.
You will need to set the value of the input element:
document.getElementById("total").value = total;
First select the particular element (i.e. total text field) in the form and set its value using assignment operator '='
document.getElementById("total").value=total;
Just assign the value in total text box after your for loop is completed
var limit = document.getElementById('limit').value;
limit = parseFloat(limit);
total = 0;
for (i=0; i<=limit ;i++) {
total = total + i;
};
document.getElementById("total").value = total;
};
use document.getElementById(put id of the text area where you want to output your answer or result).value = answer(whatever is your answer or result you want to reflect in textbox or textarea)

Loop Over Input Fields; Stop After Two Iterations

I have five form fields that will initially NOT be pre-populated with any values.
If a user fills out one of the fields, the next time they visit the form that field will be pre-populated with the value from the previous visit.
Here's what I'm trying: I'd like to create a loop that iterates through the fields. It will always check to see if there are empty fields. After finding 2 empty fields, the loop will stop and only show those 2 empty fields, while the other fields are hidden.
Here's what I have so far...I just can't figure how to stop after iterating through two fields,
HTML:
<form action="">
<input id="first" type="text" value="" />
<input id="second" type="text" value="" />
<input id="third" type="text" value="" />
<input id="fourth" type="text" value="" />
<input id="fifth" type="text" value="" />
</form>
JS:
$(document).ready(function() {
$('input').hide();
var firstValue = $('input[id="first"]').val(),
secondValue = $('input[id="second"]').val(),
thirdValue = $('input[id="third"]').val(),
fourthValue = $('input[id="fourth"]').val(),
fifthValue = $('input[id="fifth"]').val();
var firstField = $('input[id="first"]'),
secondField = $('input[id="second"]'),
thirdField = $('input[id="third"]'),
fourthField = $('input[id="fourth"]'),
fifthField = $('input[id="fifth"]');
var formValues = [firstValue, secondValue, thirdValue, fourthValue, fifthValue];
var fieldIds = [firstField, secondField, thirdField, fourthField, fifthField];
for (var i = 0; i < fieldIds.length; i++) {
for (var i = 0; i < formValues.length; i++) {
if ( formValues[i] === '' ) {
fieldIds[i].show();
return false;
}
}
}
});
Take all input fields, take the first two empty fields and show them; finally, take the complement of that to hide the rest:
var $inputFields = $('form input:text'),
$emptyFields = $inputFields
.filter(function() { return this.value == ''; })
.slice(0, 2)
.show();
$inputFields
.not($emptyFields)
.hide();
Demo
$(document).ready(function() {
$('input').hide().each( function(){
var index=0; //initilialize the counter
if( $(this).val().length ){ //check for input's length
if(index < 2) {
$(this).show();
index=index+1 //or index++ if you like
}
else {
break;
}
}
}
)};
If you want to include select and textarea fields in your eligible input population, use $(':input').hide().each(...). If you have multiple forms on your page, you would want to include that in your selector, too: $('#intended_form').find(':input').hide().each(...).
http://api.jquery.com/each/
I think that Jack provides the best answer, but this should work too. here, i use a second counter j and break the loop when j % 2 == 0, so at this time its found two empty fields. this is known as a modulus or the modulo operator.
$(document).ready(function() {
$('input').hide();
var firstValue = $('input[id="first"]').val(),
secondValue = $('input[id="second"]').val(),
thirdValue = $('input[id="third"]').val(),
fourthValue = $('input[id="fourth"]').val(),
fifthValue = $('input[id="fifth"]').val();
var firstField = $('input[id="first"]'),
secondField = $('input[id="second"]'),
thirdField = $('input[id="third"]'),
fourthField = $('input[id="fourth"]'),
fifthField = $('input[id="fifth"]');
var formValues = [firstValue, secondValue, thirdValue, fourthValue, fifthValue];
var fieldIds = [firstField, secondField, thirdField, fourthField, fifthField];
var j = 0;
for (var i = 1; i < fieldIds.length; i++) {
if ( formValues[i] === '' ) {
fieldIds[i].show();
j++;//we found an empty field
if (j % 2 == 0)
{
break;
}
}
}
});

Subtracting values from multiple input fields

I'm using the following code to take the value of one field, subtract it from the value of another field and display the result.
$(document).ready(function() {
var numIn;
var numOut;
var total;
$('#submit').click(function() {
numIn = $('input.in').val();
numOut = $('input.out').val();
total = numIn-numOut;
$('span').remove();
$('body').append('<span>£'+total+'</span>');
$('span').fadeIn(250);
});
});
I want to create a sort of income/expenditure calculator. so my question is, say I had multiple income fields and multiple expenditure fields how would I take the total value from the income fields away from the total value of the expenditure fields.
Here is an example form in case I haven't been clear.
<form>
<input class="in" type="text">
<input class="in" type="text">
<input class="in" type="text">
<input class="in" type="text">
<input class="out" type="text">
<input class="out" type="text">
<input class="out" type="text">
<input class="out" type="text">
<input type="submit" id="submit" value="Submit">
You could loop over the .in and .out fields, and add their values as you go.
Example: http://jsfiddle.net/tXPeg/3/
var numIn = 0;
var numOut = 0;
var total;
$('#submit').click(function() {
$('input.in').each(function() {
return numIn += (parseFloat(this.value) || 0);
});
$('input.out').map(function() {
return numOut += (parseFloat(this.value) || 0);
});
total = numIn - numOut;
$('span').remove();
$('body').append('<span>£' + total + '</span>');
$('span').fadeIn(250);
return false;
});​
EDIT: Changed to use parseFloat() instead of parseInt().
Actually after testing a little further the only problem is that if one or more fields are empy it returns 'NaN'.
I tried adding conditional statements to check that the field had a value but no luck:
Feel free to edit my example: http://jsfiddle.net/QaEcD/3/
$('#submit').click(function() {
var numIn = 0;
var numOut = 0;
var total = 0;
$('input.in').each(function() {
if($(this).val().length !== 0){
return numIn = numIn + parseInt(this.value);
});
});
$('input.out').map(function() {
if($(this).val().length !== 0){
return numOut = numOut + parseInt(this.value);
});
});
total = numIn-numOut;
$('span').remove();
$('body').append('<span>£'+total+'</span>');
$('span').fadeIn(250);
return false;
});
});

Categories