I have 160 inputs in my page. I want to add every 8 inputs and output it elsewhere. Instead of manually using
var total1 = inputVals[0] + inputVals[1] + inputVals[2] + inputVals[3] + inputVals[4] + inputVals[5] + inputVals[6] + inputVals[7] + inputVals[8];
I want a function with which you can just specify the starting and ending index like addarray(9, 17) and it will add all the values between and will return it. I prefer the function to be in javascript but jquery is OK.
Suppose you have <input> elements defined as:
<input type="text" class="myInput" />
<input type="text" class="myInput" />
<input type="text" class="myInput" />
...
You can create a method that does the job with the help of jQuery:
function add(start, end) {
var total = 0;
$(".myInput").slice(start, end).each(function() {
total += +this.value;
});
return total;
}
The same method in pure JavaScript will look like:
function add(start, end) {
var total = 0,
inputs = document.getElementsByClassName("myInput");
for (var i = start; i < Math.min(end, inputs.length); i++) [
total += +inputs[i].value;
});
return total;
}
Try
function calcTotal(index) {
var total = 0;
for (var i = 0; i < 9; i++) {
total += inputVals[index + i];
}
return total;
}
var total1 = calcTotal(0);
OR
function calcRangeTotal(index, count) {
var total = 0;
for (var i = 0; i < count; i++) {
total += inputVals[index + i];
}
return total;
}
var total1 = calcRangeTotal(0, 9);
Look at this:
var calculate = function() {
var sum=0;
$("input").each(function(index,element){
sum+=Number($(element).val());
});
alert(sum);
};
$(function(){
$("button").on("click",calculate);
});
Here is th jsFiddle.
var sum = 0;
function caluculate(firstIndex,secondIndex){
for(var i=one;i<secondIndex;i+=8)
sum=parseInt(sum+inputVals[i]);
}
function addarray($start,$end) {
var total = 0;
for(var i = $start; i < $end; i++)
total += inputVals[i];
return total;
}
var myTotal = addarray(9,17);
Related
Right now I have two different functions that calculate the total costs of two different sections on the menu, the Appetizers & Main Dishes. Now what I am trying to do is create a third function that will give me a grand total of both the Appetizers & Main Dishes costs.
Here are my two functions:
function AppSubTotal() {
var guestsQTY = +document.getElementById('guests').value || 0,
input = document.getElementsByName("app"),
appItemTotal = 0;
var appsubtotal = 0;
for (var i = 0; i < input.length; i++) {
if (input[i].checked) appItemTotal += +input[i].value;
}
document.getElementById("appsubtotal").value = "$" + (appItemTotal * guestsQTY * percentage).toFixed(2);
appsubtotal.innerText = appsubtotal;
}
function MainDishSubTotal() {
var guestsQTY = +document.getElementById('guests').value || 0,
input = document.getElementsByName("maindish"),
maindishItemTotal = 0;
var maindishtotal = 0;
for (var i = 0; i < input.length; i++) {
if (input[i].checked) maindishItemTotal += +input[i].value;
}
document.getElementById("maindishtotal").value = "$" + (maindishItemTotal * guestsQTY * percentage).toFixed(2);
maindishtotal.innerText = maindishtotal;
}
This is how I have the Appetizers Total & Main Dishes Total displayed in HTML
<label>
<h1>
Total Appetizers Costs:
<input value="$0.00" readonly="readonly" type="text" id="appsubtotal"/>
</h1>
</label>
<label>
<h1>
Total Main Dish Costs:
<input value="$0.00" readonly="readonly" type="text" id="maindishtotal"/>
</h1>
</label>
I started a new function that will hold the grand total. I tried following another tutorial on how this can be done but it doesn't seem to be working for me but this is what I have so far.
function GrandTotal() {
var totalApp = appsubtotal.innerText || 0;
var totalMain = maindishtotal.innerText || 0;
document.getElementById('grandtotal').innerText = Number(totalApp) + Number(totalMain);
}
document.addEventListener('keyup', function() {
AppSubTotal();
MainDishSubTotal();
});
And then I want the grand total to be updated automatically as the user is selecting different items of the menu in HTML like this:
<label>
<h1>
Your Grand Total is:
<input value="$0.00" readonly="readonly" type="text" id="grandtotal"/>
</h1>
</label>
You need to call GrandTotal() at the end of each of other 2 functions:
function AppSubTotal() {
var guestsQTY = +document.getElementById('guests').value || 0,
input = document.getElementsByName("app"),
appItemTotal = 0;
var appsubtotal = 0;
for (var i = 0; i < input.length; i++) {
if (input[i].checked) appItemTotal += +input[i].value;
}
document.getElementById("appsubtotal").value = "$" + (appItemTotal * guestsQTY * percentage).toFixed(2);
appsubtotal.innerText = appsubtotal; //here sub total updated
GrandTotal();
}
function MainDishSubTotal() {
var guestsQTY = +document.getElementById('guests').value || 0,
input = document.getElementsByName("maindish"),
maindishItemTotal = 0;
var maindishtotal = 0;
for (var i = 0; i < input.length; i++) {
if (input[i].checked) maindishItemTotal += +input[i].value;
}
document.getElementById("maindishtotal").value = "$" + (maindishItemTotal * guestsQTY * percentage).toFixed(2);
maindishtotal.innerText = maindishtotal; //here main dish updated
GrandTotal();
}
function AppSubTotal() {
...
return appsubtotal; // assuming this is a number
}
function MainDishSubTotal() {
...
return maindishtotal; // assuming this is a number
}
... // in some other function
const checkTotal = MainDishSubtotal() + AppSubTotal();
// do whatever you want with this value now, including putting it as the text value somewhere
I don't know the full context of your code, but a little refactoring can help you out:
// it is better to keep compoments references if you are going to use them
// more tha once
var appSubtotalField = document.getElementById("appsubtotal");
function setAppSubTotal() {
appSubtotalField.value = "$" + calculateAppSubTotal().toFixed(2);
appsubtotal.innerText = appsubtotal;
}
function calculateAppSubTotal() {
var guestsQTY = document.getElementById('guests').value || 0,
input = document.getElementsByName("app"),
appItemTotal = 0;
var appsubtotal = 0;
for (var i = 0; i < input.length; i++) {
if (input[i].checked) appItemTotal += input[i].value;
}
return appItemTotal * guestsQTY * percentage;
}
var mainDishTotalField = document.getElementById("maindishtotal");
function setMainDishSubTotal() {
mainDishTotalField.value = "$" + calculateMainDishTotal().toFixed(2);
maindishtotal.innerText = maindishtotal;
}
function calculateMainDishTotal() {
var guestsQTY = document.getElementById('guests').value || 0,
input = document.getElementsByName("maindish"),
maindishItemTotal = 0;
var maindishtotal = 0;
for (var i = 0; i < input.length; i++) {
if (input[i].checked) maindishItemTotal += input[i].value;
}
return maindishItemTotal * guestsQTY * percentage;
}
function setGrandTotal() {
document.getElementById('grandtotal').innerText =
calculateAppSubTotal() + calculateMainDishTotal();
}
Then you can complete your initialization
This currently listens to every keyup event. You may want to add a button or other mechanism to trigger this calculation.
document.addEventListener('keyup', function() {
setAppSubTotal();
setMainDishSubTotal();
});
I need to change a calculation from input name(s) to input id(s).
The old input name was "ef-fee".
The new id is "ef-fee_" +[i]);
The old code using input names:
<script async> //Entrance Fees
function findTotalEF(){
var arrEF = document.getElementsByName('ef-fee');
var totEF=0;
for(var i=0; i<arrEF.length; i++){
if(parseInt(arrEF[i].value)) totEF += parseInt(arrEF[i].value);}
document.getElementById('totalEF').value = totEF;
}
This is the new code which doesn't work:
<script async> //Entrance Fees
function findTotalEF(){
var totEF=0;
for (i=0; i <=48; i++)
if ($('#ef-fee_' + i > 0)) {totEF += "ef-fee_" +[i].val;} // This line is not correct. Can someone please fix it?
document.getElementById('totalEF').value = totEF;
}
Should do what you are needing
function findTotalEF() {
var totEF = 0;
for (var i = 0; i <= 48; i++) {
var $input = $('#ef-fee_' + i);
var value = parseInt($input.val()) || 0;
totEF += value > 0 ? value : 0;
}
$('#totalEF').val(totEF);
}
i have some code that takes input numbers and put them into a new array. How can i make it so my alert tells the user how many times the number is represented in the input? Exampel 0,4,4,2,3,4,1 would show "0 appears 1 time, 4 appears 3 times" and so on...I think im close but cant get the final part right...
<!DOCTYPE html>
<html>
<head>
<title>Oppgave 5</title>
<script type="text/javascript">
window.onload = btn;
function btn() {
document.getElementById("btn").onclick = showTxt;
}
function showTxt() {
var text = "";
var input = document.getElementById("input").value;
var split = input.split(",");
var newArray = split;
var count = 0;
for (var i = 0; i < newArray.length; i++) {
if (newArray[i] === parseInt(input)) {
count++;
}
alert("Number " + newArray[i] + " appears " + count + " times");
}
text += newArray;
document.getElementById("print").innerHTML = text;
}
</script>
</head>
<body>
<input id="input" type="text">
<button id="btn" type="button">Show</button>
<p id="print"></p>
</body>
</html>
I have changed your showTxt function
function showTxt() {
var text = "";
var input = document.getElementById("input").value;
var split = input.split(",");
var newArray = split;
var count;
for (var i = 0; i < newArray.length; i++) {
count = 0;
for (var j = 0; j < newArray.length; j++) {
if (newArray[i] === newArray[j]) {
count++;
}
}
alert("Number " + newArray[i] + " appears " + count + " times");
}
text += newArray;
document.getElementById("print").innerHTML = text;
}
You could use the method from this gist like so:
window.onload = btn;
function btn() {
document.getElementById("btn").onclick = showTxt;
}
function showTxt() {
var text = "";
var input = document.getElementById("input").value;
var split = input.replace(/ /g, '').split(",").sort();
compressArray(split);
}
function compressArray(original) {
var compressed = [];
// make a copy of the input array
var copy = original.slice(0);
// first loop goes over every element
for (var i = 0; i < original.length; i++) {
var myCount = 0;
// loop over every element in the copy and see if it's the same
for (var w = 0; w < copy.length; w++) {
if (original[i] == copy[w]) {
// increase amount of times duplicate is found
myCount++;
// sets item to undefined
delete copy[w];
}
}
if (myCount > 0) {
var a = new Object();
a.value = original[i];
a.count = myCount;
compressed.push(a);
}
}
for (var i = 0; i < compressed.length; i++) {
var message = compressed[i].value + ' appears ' + compressed[i].count + ' times.';
alert(message);
document.getElementById("print").innerHTML += message + '</br>';
}
};
<input id="input" type="text">
<button id="btn" type="button">Show</button>
<p id="print"></p>
Check this out, may be it'll helpful .
<!DOCTYPE html>
<html>
<head>
<title>Oppgave 5</title>
<script type="text/javascript">
window.onload = btn;
function btn() {
document.getElementById("btn").onclick = showTxt;
}
function showTxt() {
var text = "";
var input = document.getElementById("input").value;
var split = input.split(",");
var newArray = split;
let countedValues = newArray.reduce(function(obj,val){
if(obj[val])
obj[val] += 1;
else
obj[val] = 1;
return obj
}, {})
for (let value in countedValues ) {
alert("Number " + value + " appears " + countedValues[value] + " times");
}
text = newArray;
document.getElementById("print").innerHTML = text;
}
</script>
</head>
<body>
<input id="input" type="text">
<button id="btn" type="button">Show</button>
<p id="print"></p>
</body>
</html>
How to ensure i have a dynamic increment of Alphabets in a new cell on left side, next to each cell in a row which is dynamically created based on the option chosen in Select. This newly generated alphabet will be considered as bullet points/serial number for that particular row's text box.
jsfiddle
js code
$(document).ready(function(){
var select = $("#Number_of_position"), table = $("#Positions_names");
for (var i = 1; i <= 100; i++){
select.append('<option value="'+i+'">'+i+'</option>');
}
select.change(function () {
var rows = '';
for (var i = 0; i < $(this).val(); i++) {
rows += "<tr><td><input type='text'></td></tr>";
}
table.html(rows);
});
});
html
<select id="Number_of_position">
</select> <table id="Positions_names">
</table>
This is essentially a base26 question, you can search for an implementation of this in javascript pretty easily - How to create a function that converts a Number to a Bijective Hexavigesimal?
alpha = "abcdefghijklmnopqrstuvwxyz";
function hex(a) {
// First figure out how many digits there are.
a += 1; // This line is funky
var c = 0;
var x = 1;
while (a >= x) {
c++;
a -= x;
x *= 26;
}
// Now you can do normal base conversion.
var s = "";
for (var i = 0; i < c; i++) {
s = alpha.charAt(a % 26) + s;
a = Math.floor(a/26);
}
return s;
}
So you can do
$(document).ready(function(){
var select = $("#Number_of_position"), table = $("#Positions_names");
for (var i = 1; i <= 100; i++){
select.append('<option value="'+i+'">'+i+'</option>');
}
select.change(function () {
var rows = '';
for (var i = 0; i < $(this).val(); i++) {
rows += "<tr><td>" + hex(i) + "</td><td><input type='text'></td></tr>";
}
table.html(rows);
});
});
Heres the example http://jsfiddle.net/v2ksyy7L/6/
And if you want it to be uppercase just do
hex(i).toUpperCase();
Also - this will work up to any number of rows that javascript can handle
if i have understood you correctly, that's maybe what you want:
http://jsfiddle.net/v2ksyy7L/3/
I have added an array for the alphabet:
var alphabet = "abcdefghijklmnopqrstuvwxyz".split("");
and then added the output to your "render" loop:
rows += "<tr><td>" + alphabet[i] + " <input type='text'></td></tr>";
I have found a pretty stuff for rating entries: http://www.fyneworks.com/jquery/star-rating/. It's good and easy. But I still need some more.
My code:
<div data-rating="4/5" class="entry"></div>
Desired function:
function init_rating(rate) { //... }
$(".entry").html( init_rating($(this).attr("data-rating")) );
Thanks much,
Here:
function init_rating(selector) {
var entry = $(selector);
var output = "";
var input = "<input name=\"star\" type=\"radio\" class=\"star\""
var checked = " checked=\"checked\"";
var close = "/>";
var params = entry.attr("data-rating").split("/", 2);
var rating = parseInt(params[0]);
var total = parseInt(params[1]);
for (var i = 0; i < total; i++) {
output += input;
if (i == rating - 1) output += checked;
output += close;
}
entry.html(output);
$('input[type=radio].star').rating();
}
init_rating(".entry");
fiddle: http://jsfiddle.net/qcxvW/20/