i want to calculate the total of the numbers entered by the user. After a user has added item name and the amount, i want to display the total. How can i do this? i just need to display the total.
For example
item name : 10
item name : 5
total = 15
http://jsfiddle.net/81t6auhd/
<body>
<header>
<h1>Exercise 5-2</h1>
</header>
<p>Item: <input type="text" id="item" size="30">
<p>Amount: <input type="text" id="amount" size="30">
<p><span id="message">*</span>
<p><input type="button" id="addbutton" value="Add Item" onClick="processInfo();">
<script>
var $ = function(id) {
return document.getElementById(id);
};
var myTransaction = [];
function processInfo ()
{
var myItem = $('item').value;
var myAmount = parseFloat($('amount').value);
var myTotal = myItem + ":" + myAmount;
var myParagraph = $('message');
myParagraph.innerHTML = "";
myTransaction.push(myTotal);
myParagraph.innerHTML += myTransaction.join("<br>");
};
(function () {
$("addbutton").onclick = processInfo;
})();
</script>
</body>
you have to stored the previous value somewhere in memory to be able to reuse it at next iteration
one proposal can be to stored it in dataset of the field
if ($('amount').dataset.previous) {
myAmount += parseFloat($('amount').dataset.previous);
}
$('amount').dataset.previous = myAmount
var $ = function(id) {
return document.getElementById(id);
};
var myTransaction = [];
function processInfo ()
{
var myItem = $('item').value;
var myAmount = parseFloat($('amount').value);
if ($('amount').dataset.previous) {
myAmount += parseFloat($('amount').dataset.previous);
}
$('amount').dataset.previous = myAmount;
var myTotal = myItem + ":" + myAmount;
var myParagraph = $('message');
myParagraph.innerHTML = "";
myTransaction.push(myTotal);
myParagraph.innerHTML += myTransaction.join("<br>");
};
(function () {
$("addbutton").onclick = processInfo;
})();
<p>Item: <input type="text" id="item" size="30">
<p>Amount: <input type="text" id="amount" size="30">
<p><span id="message">*</span>
<p><input type="button" id="addbutton" value="Add Item" onClick="processInfo();">
Related
function sum()
{
$(document).on('keyup', "*[data-field='unit'],*[data-field='unit_price']", function(e)
{
var unit = document.getElementById('unit').value;
var unitPrice = document.getElementById('unit_price').value;
var result = parseInt(unit) * parseInt(unitPrice);
if (!isNaN(result))
{
document.getElementById('amount').value = result;
}
});
}
p/s: this only function at normal form. but not dynamic form.
[edit ?]
$('#unit, #price').on('input',function()
{
let qty = parseInt($('#unit').val())
, price = parseFloat($('#price').val())
;
$('#amount').val((qty * price ? qty * price : 0).toFixed(2));
});
you can do this whit jQuery Plugin i write simple one
you can test it on this :
$.fn.sum = function(options) {
"use strict";
var self = this;
self.defaults = {
unit : '[data-field="unit"]',
unit_price : '[data-field="unit_price"]',
result : '[data-field="amount"]',
onCalculate : function(result){},
};
self.settings = $.extend({},self.defaults, options );
var unit_count = $(self).find('input'+self.settings.unit).length;
var unit_price_count = $(self).find('input'+self.settings.unit_price).length;
if(unit_count > 0 && unit_price_count > 0){
var unit, unit_price=0, result=0;
$($(self).find('input'+self.settings.unit_price)).bind('keyup', function(){
unit = $(this).closest('form').find('input'+self.settings.unit).val();
unit_price = $(this).closest('form').find('input'+self.settings.unit_price).val();
result = sum(unit, unit_price);
self.settings.onCalculate(self, $(this), result);
});
$($(self).find('input'+self.settings.unit)).bind('keyup', function(){
unit = $(this).closest('form').find('input'+self.settings.unit).val();
unit_price = $(this).closest('form').find('input'+self.settings.unit_price).val();
result = sum(unit, unit_price);
self.settings.onCalculate(self, $(this), result);
});
function sum(unit, unit_price){
var result = parseInt(unit) * parseInt(unit_price);
if (!isNaN(result)) {
return result;
}
}
}
}
$(document).ready(function(){
$('form').sum({
onCalculate: function(self, active, result){
$(active).closest('form').find(self.settings.result).val(result);
},
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form id="fff33">
<legend>
two
</legend>
<lable>unit</lable>
<input type="text" data-field='unit' id="unit22">
<br>
<lable>unit_price</lable>
<input type="text" data-field='unit_price' id="unit_price22">
<input type="text" data-field="amount" disabled>
</form>
<br>
<br><br>
<form id="fff">
<legend>
one
</legend>
<lable>unit</lable>
<input type="text" data-field='unit' id="unit">
<br>
<lable>unit_price</lable>
<input type="text" data-field='unit_price' id="unit_price">
<input type="text" data-field="amount" disabled>
</form>
<br><br>
Apologies for the poorly-worded question. It's my first question here!
I am trying to make an application whereby one can log the scores of players from any game and see the results at the end of the game (see the code snippet below).
So far, I have managed to push players and their scores (initially empty arrays) into the main array and thereby presented these players in a list (see below):
HTML
<h1>Score Keeper</h1>
<input type="text" placeholder="Enter Player's Name" id="enterPlayer">
<input type="submit" id="enterPlayerBtn" value="Enter Player">
<div>
<ul id="scoreConsole"></ul>
</div>
JavaScript
var players = [];
var enterPlayer = document.querySelector("#enterPlayer");
var enterPlayerBtn = document.querySelector("#enterPlayerBtn");
var scoreConsole = document.querySelector("#scoreConsole");
//PUSHES OBJECTS INTO ARRAYS OF PLAYERS
addPlayer = () => {
var entered = enterPlayer.value;
players.push(
{
player: entered,
score: []
}
);
enterPlayer.value = "";
}
//DISPLAYS PLAYERS ENTERED INTO ARRAY:
var i=0;
createdPlayers = () => {
var toAdd = document.createDocumentFragment();
var newLi = document.createElement("li");
newLi.className="each-player";
newLi.innerHTML = players[i].player + " " + "<input type='number' placeholder='enter score' class='enterScore'>" + "<input type='submit' class='submitScoreBtn'>";
toAdd.appendChild(newLi);
i++;
scoreConsole.appendChild(toAdd);
}
enterPlayerBtn.addEventListener("click", () => {
addPlayer();
createdPlayers();
});
This gives me a list with the players' names, inputs to enter scores and buttons to log the scores. So far, so good.
But...
I am just trying to get each button to work. As you can see above, I gave each submit button classes ("submitScoreBtn"). I'm at the stage where I want to make sure that my new buttons work. Here's my code so far:
var enterScore = document.querySelectorAll(".enterScore");
var submitScore = document.querySelectorAll(".submitScoreBtn");
for (var x = 0; x < submitScore.length; x++){
submitScore[x].addEventListener("click", () => {
alert("selected");
});
}
I initially was getting errors without adding a for loop. Now I don't get any errors, but I also don't get any alerts. I'm just not sure why these buttons do not work.
Please see the code snippet below.
var players = [];
var enterPlayer = document.querySelector("#enterPlayer");
var enterPlayerBtn = document.querySelector("#enterPlayerBtn");
var scoreConsole = document.querySelector("#scoreConsole");
//PUSHES OBJECTS INTO ARRAYS OF PLAYERS
addPlayer = () => {
var entered = enterPlayer.value;
players.push(
{
player: entered,
score: []
}
);
enterPlayer.value = "";
}
//DISPLAYS PLAYERS ENTERED INTO ARRAY:
var i=0;
createdPlayers = () => {
var toAdd = document.createDocumentFragment();
var newLi = document.createElement("li");
newLi.className="each-player";
newLi.innerHTML = players[i].player + " " + "<input type='number' placeholder='enter score' class='enterScore'>" + "<input type='submit' class='submitScoreBtn'>";
toAdd.appendChild(newLi);
i++;
scoreConsole.appendChild(toAdd);
}
enterPlayerBtn.addEventListener("click", () => {
addPlayer();
createdPlayers();
});
var enterScore = document.querySelectorAll(".enterScore");
var submitScore = document.querySelectorAll(".submitScoreBtn");
for (var x = 0; x < submitScore.length; x++){
submitScore[x].addEventListener("click", () => {
alert("selected");
});
}
<html>
<head>
<title>Score</title>
</head>
<body>
<h1>Score Keeper</h1>
<input type="text" placeholder="Enter Player's Name" id="enterPlayer">
<input type="submit" id="enterPlayerBtn" value="Enter Player">
<div>
<ul id="scoreConsole"></ul>
</div>
<script src="game.js"></script>
</body>
</html>
Being as you're dynamically creating the buttons, it might be easier to simply add the function to the button's onclick.
You can still access the event object from this click by sending it as a parameter, like:
<input type='submit' onclick='submitScoreClick(event)' class='submitScoreBtn'>
var players = [];
var enterPlayer = document.querySelector("#enterPlayer");
var enterPlayerBtn = document.querySelector("#enterPlayerBtn");
var scoreConsole = document.querySelector("#scoreConsole");
//PUSHES OBJECTS INTO ARRAYS OF PLAYERS
addPlayer = () => {
var entered = enterPlayer.value;
players.push(
{
player: entered,
score: []
}
);
enterPlayer.value = "";
}
//DISPLAYS PLAYERS ENTERED INTO ARRAY:
var i=0;
createdPlayers = () => {
var toAdd = document.createDocumentFragment();
var newLi = document.createElement("li");
newLi.className="each-player";
newLi.innerHTML = players[i].player + " " + "<input type='number' placeholder='enter score' class='enterScore'>" + "<input type='submit' onclick='submitScoreClick(event)' class='submitScoreBtn'>";
toAdd.appendChild(newLi);
i++;
scoreConsole.appendChild(toAdd);
}
enterPlayerBtn.addEventListener("click", () => {
addPlayer();
createdPlayers();
});
var enterScore = document.querySelectorAll(".enterScore");
var submitScore = document.querySelectorAll(".submitScoreBtn");
function submitScoreClick (e) {
alert("selected");
};
<html>
<head>
<title>Score</title>
</head>
<body>
<h1>Score Keeper</h1>
<input type="text" placeholder="Enter Player's Name" id="enterPlayer">
<input type="submit" id="enterPlayerBtn" value="Enter Player">
<div>
<ul id="scoreConsole"></ul>
</div>
<script src="game.js"></script>
</body>
</html>
At the point in time when this code is run:
for (var x = 0; x < players.length; x++){
submitScore[x].addEventListener("click", (event) => {
event.alert("selected");
});
}
players.length is equal to 0. So the code is essentially never executed.
remove the for loop and add this code
document.addEventListener('click', function (event) {
if ( event.target.classList.contains( 'submitScoreBtn' ) ) {
alert("selected");
}
}, false);
var players = [];
var enterPlayer = document.querySelector("#enterPlayer");
var enterPlayerBtn = document.querySelector("#enterPlayerBtn");
var scoreConsole = document.querySelector("#scoreConsole");
//PUSHES OBJECTS INTO ARRAYS OF PLAYERS
addPlayer = () => {
var entered = enterPlayer.value;
players.push({
player: entered,
score: []
});
enterPlayer.value = "";
}
//DISPLAYS PLAYERS ENTERED INTO ARRAY:
var i = 0;
createdPlayers = () => {
var toAdd = document.createDocumentFragment();
var newLi = document.createElement("li");
newLi.className = "each-player";
newLi.innerHTML = players[i].player + " " + "<input type='number' placeholder='enter score' class='enterScore'>" + "<input type='submit' class='submitScoreBtn'>";
toAdd.appendChild(newLi);
i++;
scoreConsole.appendChild(toAdd);
}
document.addEventListener('click', function(event) {
if (event.target.classList.contains('submitScoreBtn')) {
alert("selected");
}
}, false);
enterPlayerBtn.addEventListener("click", () => {
addPlayer();
createdPlayers();
});
var enterScore = document.querySelectorAll(".enterScore");
<html>
<head>
<title>Score</title>
</head>
<body>
<h1>Score Keeper</h1>
<input type="text" placeholder="Enter Player's Name" id="enterPlayer">
<input type="submit" id="enterPlayerBtn" value="Enter Player">
<div>
<ul id="scoreConsole"></ul>
</div>
<script src="game.js"></script>
</body>
</html>
The easiest solution is to use variables and createElement just like you do with toAdd. This way each created entry will remember its own inputs (local variables to the function), and you can use for example the score input variable in the click handler without confusion of which number input belongs to which entry.
I removed the class for the inputs because it's not needed to select them anymore, but you can still add some for styling for example. If you want to add classes to select them all, be sure to run querySelectorAll each time, so that added elements are actually selected.
var players = [];
var enterPlayer = document.querySelector("#enterPlayer");
var enterPlayerBtn = document.querySelector("#enterPlayerBtn");
var scoreConsole = document.querySelector("#scoreConsole");
//PUSHES OBJECTS INTO ARRAYS OF PLAYERS
var addPlayer = () => {
var entered = enterPlayer.value;
players.push(
{
player: entered,
score: []
}
);
enterPlayer.value = "";
}
//DISPLAYS PLAYERS ENTERED INTO ARRAY:
var i=0;
var createdPlayers = () => {
var toAdd = document.createDocumentFragment();
var newLi = document.createElement("li");
newLi.className="each-player";
newLi.innerHTML = players[i].player + " ";
var enterScore = document.createElement("input");
enterScore.type = 'number';
enterScore.placeholder = 'enter score';
var submitScore = document.createElement("input");
submitScore.type = 'submit';
submitScore.addEventListener("click", () => {
alert("selected score: " + enterScore.value);
});
newLi.appendChild(enterScore);
newLi.appendChild(submitScore);
toAdd.appendChild(newLi);
i++;
scoreConsole.appendChild(toAdd);
}
enterPlayerBtn.addEventListener("click", () => {
addPlayer();
createdPlayers();
});
<html>
<head>
<title>Score</title>
</head>
<body>
<h1>Score Keeper</h1>
<input type="text" placeholder="Enter Player's Name" id="enterPlayer">
<input type="submit" id="enterPlayerBtn" value="Enter Player">
<div>
<ul id="scoreConsole"></ul>
</div>
<script src="game.js"></script>
</body>
</html>
I'm trying to add my getExamGrades and getLabGrades together by calling my other function to get a total grade but nothing I've tried works. Everything I've done so far just eliminates both of the functions I call and leaves everything blank. The code below works perfectly fine, just need help with the last part and then I can figure out the other variables and functions.
<!DOCTYPE html>
<html>
<header>
<script>
function getExamGrades()
{
var exam1 = document.getElementById("Exam1").value;
var exam2 = document.getElementById("Exam2").value;
var exam3 = document.getElementById("Exam3").value;
var Exams = Number(exam1) + Number(exam2) + Number(exam3);
document.getElementById("examGrade").innerHTML = Exams;
}
function getLabGrades()
{
var lab1 = document.getElementById("Lab1").value;
var lab2 = document.getElementById("Lab2").value;
var lab3 = document.getElementById("Lab3").value;
var Labs = Number(lab1) + Number(lab2) + Number(lab3);
document.getElementById("labGrade").innerHTML = Labs;
}
function getTotalGrades()
{
//var Total = Number(getExamGrades()) + Number(getLabGrades();
document.getElementByID("totalGrade").innerHTML = Total;
}
</script>
</header>
<body>
Exam1: <input type = "text" name="Exam1" value ="100" id="Exam1">
Exam2: <input type = "text" name="Exam2" value ="100" id="Exam2">
Exam3: <input type = "text" name="Exam3" value ="100" id="Exam3">
<br><br>
<button onClick="getExamGrades()"> Calculate Exam Grade </button>
Total: <output id="examGrade"> </output>
<br><br>
Lab1: <input type = "text" name="Lab1" value ="100" id="Lab1">
Lab2: <input type = "text" name="Lab2" value ="100" id="Lab2">
Lab3: <input type = "text" name="Lab3" value ="100" id="Lab3">
<br><br>
<button onClick="getLabGrades()"> Calculate Lab Grade </button>
Total: <output id="labGrade"> </output>
<br><br>
<button onClick="getTotalGrades()"> Calculate Total Grade </button>
Final Grade: <output id="totalGrade"> </output>
</body>
</html>
Your functions are not returning the values. If they did, then what you were trying would work. Try it like this:
function getExamGrades()
{
var exam1 = document.getElementById("Exam1").value;
var exam2 = document.getElementById("Exam2").value;
var exam3 = document.getElementById("Exam3").value;
var Exams = Number(exam1) + Number(exam2) + Number(exam3);
document.getElementById("examGrade").innerHTML = Exams;
return Exams;
}
function getLabGrades()
{
var lab1 = document.getElementById("Lab1").value;
var lab2 = document.getElementById("Lab2").value;
var lab3 = document.getElementById("Lab3").value;
var Labs = Number(lab1) + Number(lab2) + Number(lab3);
document.getElementById("labGrade").innerHTML = Labs;
return Labs;
}
function getTotalGrades()
{
var Total = Number(getExamGrades()) + Number(getLabGrades());
document.getElementById("totalGrade").innerHTML = Total;
}
There were a couple of other minor issues that I fixed for you too.
You can see a working example here: http://jsfiddle.net/8js5uewc/2/
getting no errors but trying to loop through all the inputs and add them all to the total (var = paidTotal). The first input works but the rest don't when others are added with an add button. Something wrong with the loop?
$(document).ready(function() {
var maxFields = 20;
var addButton = $('#plusOne');
var deleteButton = $('#minusOne');
var wrapper = $('#userNumbers');
var fieldInput = '<div><input type="text" name="persons" id="persons"/></div>';
var x = 1;
$(addButton).click(function () {
if (x < maxFields) {
x++;
$(wrapper).append(fieldInput);
}
});
$(deleteButton).click(function(e) {
e.preventDefault();
var myNode = document.getElementById("userNumbers");
i=myNode.childNodes.length - 1;
if(i>=0){
myNode.removeChild(myNode.childNodes[i]);
x--;
}
});
});
function peoplePaid() {
var checkTotal = document.getElementById('check').value;
var personsCheck = document.getElementById('personsCheck').value;
var paidTotal = document.getElementById('paidTotal');
for(var i = 1; i < personsCheck.length; i+=1){
personsCheck[i] += paidTotal;
}
paidTotal.innerHTML = checkTotal - personsCheck;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
$ <input type="text" id="check" value="" />
<button type="button" id="plusOne">+</button>
<button type="button" id="minusOne">-</button>
<div id="userNumbers">
<div class="">
<input type="text" id="personsCheck" name="person">
</div>
<button onclick="peoplePaid()">Calculate</button>
<!--Paid Amount-->
<div>
<h3>Paid Amount: <span id="paidTotal"></span></h3>
</div>
make it as class
<input type="text" class="personsCheck" name="person">
and access it by
var personsCheck = document.getElementsByClassName('personsCheck');
ids have to be unique. You'll only get one element from document.getElementById().
Try using a class instead, something like
var fieldInput = '<div><input type="text" name="persons" class="persons"/></div>';
and use document.getElementsByClassName('persons') to get an array of all of the input fields that have that class.
Your code logic is not something what you want to achieve.
I can not find any logic to use the input element with id=personsCheck.
First of all, you are appending input element with same id again and again which is invalid, because in a document id attribute must be unique. Use class attribute instead.
To get the total you can first get the elements with querySelectorAll(), theb use forEach() to loop through all of them to add one by one.
$(document).ready(function() {
var maxFields = 20;
var addButton = $('#plusOne');
var deleteButton = $('#minusOne');
var wrapper = $('#userNumbers');
var fieldInput = '<div><input type="text" name="persons" class="persons"/></div>';
var x = 1;
$(addButton).click(function () {
if (x < maxFields) {
x++;
$(wrapper).append(fieldInput);
}
});
$(deleteButton).click(function(e) {
e.preventDefault();
var myNode = document.getElementById("userNumbers");
i=myNode.childNodes.length - 1;
if(i>=0){
myNode.removeChild(myNode.childNodes[i]);
x--;
}
});
});
function peoplePaid() {
var checkTotal = Number(document.getElementById('check').value);
var persons = document.querySelectorAll('.persons');
var personsCheck = Number(document.getElementById('personsCheck').value)
var paidTotal = document.getElementById('paidTotal');
var total = 0;
persons.forEach(function(p){
total += Number(p.value);
});
paidTotal.textContent = checkTotal - total;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
$ <input type="text" id="check" value="" />
<button type="button" id="plusOne">+</button>
<button type="button" id="minusOne">-</button>
<div id="userNumbers">
<div class="">
<input type="text" id="personsCheck" name="person">
</div>
<button onclick="peoplePaid()">Calculate</button>
<!--Paid Amount-->
<div>
<h3>Paid Amount: <span id="paidTotal"></span></h3>
</div>
I have 3 bootstrap sliders, which are basically input fields. The values of these sliders get displayed into an input box, and below that a price value is displayed. What I need to do is to save those 4 values to an array whenever a button is clicked. I managed to do this with the values hardcoded and without a button like this:
<li> <a class = "add-to-cart" href = "#" data-name = "Windows" data-price = "99.95" data-ram ="1" data-diskSpace="30" data-cpu="3">
<script>
$(".add-to-cart").click(function(event){
event.preventDefault(); // prevents the links from doing their default behaviour
var name = $(this).attr("data-name");
var price = Number($(this).attr("data-price"));
var ram = Number($(this).attr("data-ram"));
var diskSpace =Number($(this).attr("data-diskSpace"));
var cpu = Number($(this).attr("data-cpu"));
addItemToCart(name,price,1,ram,diskSpace,cpu);
displayCart();
});
var cart = [];
var Item = function (name,price,quantity,ram,diskSpace,cpu){
this.name = name;
this.price = price;
this.quantity = quantity;
this.ram = ram;
this.diskSpace = diskSpace;
this.cpu = cpu;
};
//addItemToCart(name,price,quantity)
function addItemToCart(name,price,quantity,ram,diskSpace,cpu){
for (var i in cart){
if(cart[i].name === name){
cart[i].quantity +=quantity;
saveCart();
return;
}
}
var item = new Item(name,price,quantity,ram,diskSpace,cpu);
cart.push(item);
}
</script>
This is my code for the values from the input box :
<input class="slider" id="ram" data-slider-id='ex1Slider' type="text" data-slider-min="0" data-slider-max="10" data-slider-step="1" />
<hr />
<input class="slider" id="diskSpace" data-slider-id='ex1Slider2' type="text" data-slider-min="0" data-slider-max="100" data-slider-step="10" />
<hr />
<input class="slider" id="cpu" data-slider-id='ex1Slider3' type="text" data-slider-min="0" data-slider-max="4" data-slider-step="1" />
<hr />
<input type="text" class="form-control" id="inputValue" value="0" />
</div>
Prijs:
<div id = "prijs">
</div>
<script>
var minSliderValue = $("#ram").data("slider-min");
var maxSliderValue = $("#ram").data("slider-max");
$('#ram').slider({
value : 0,
formatter: function(value) {
return 'RAM: ' + value + 'GB';
}
});
$('#diskSpace').slider({
value : 0,
formatter: function(value) {
return 'Disk Space: ' + value + 'GB';
}
});
$('#cpu').slider({
value : 0,
formatter: function(value) {
return 'CPU : ' + value + ' Cores';
}
});
// If You want to change input text using slider handler
$('#ram, #diskSpace, #cpu').on('slide', function(slider){
var ram = parseFloat($('#ram').val());
var diskSpace = parseFloat($('#diskSpace').val());
var cpu = parseFloat($('#cpu').val());
$("#inputValue").val("RAM="+ ram + "GB, Disk=" +diskSpace + "GB, Core="+cpu);
var totalPrice=(parseFloat(ram)*3.5 + parseFloat(diskSpace)*0.15+ parseFloat(cpu)*6.5).toFixed(2);
$("#prijs").html(totalPrice);
});
</script>
working jsfiddle for the sliders function: http://jsfiddle.net/umxhhqy4/8/