Add values from input to array on button click - javascript

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/

Related

Calculate total sum of all the numbers previously entered in a field

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();">

Add 2 functions

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/

Pass entered value from one table to another table using javascript

I want to pass the entered value to table two when user I click add, the quantity will be added to the second table. When I click Add button quantity is displayed as an empty value. But not console this shows the entered quantity
The quantity is of the same name and the quantityEntered is of the same name. When I inspect element I get the value entered on the...
"quantityEntered": <input type="text" id="CLT-K809S/SEE_quantity" name="quantityEntered" class="form-control" onkeypress="return isNumber(event)" readonly=readonly value="1" />
...on every row of my new table.
Here is my code:
function saveEneteredQuantity() {
var quantity;
var quantityName;
var getEnteredQuantity;
var enteredQuatity;
var getIndex;
var textvalue = "";
quantity = document.getElementsByName("quantity").length;
quantityName = document.getElementsByName('quantity').value;
console.log("Count the lenght of the input textbox on the HO Stock : ", quantity);
document.getElementsByName("quantityEntered").value = quantityName;
getEnteredQuantity = quantity;
for (var i = 0; i < quantity; i++) {
textvalue = textvalue + document.getElementsByName("quantity").item(i).value;
}
$('[name="quantity"]').each(function(index) {
getIndex = $(this).val();
enteredQuatity = $('[name="quantity"]').eq(index).val();
});
quantity = textvalue;
alert("This was provided: ", quantity);
debugger;
console.log("Check the grapped quantity on table of Selected Line Items to Order : ", quantity);
if (quantity == '' || quantity == 0) {
alert("Quantity can not 0.\n Please enter quantity which is less than available quantity");
}
console.log("Entered Quantity: ", quantity);
}
var items = [{
"avalaibleQty": '<input type="text" id="CLT-C659S/SEE_avaliableQuantity" name="avaliableQuantity" class="form-control" readonly="readonly" value="1">',
"quantityEntered": '<input type="text" id="quantityEntered" name="quantityEntered" readonly="readonly" class="form-control" />',
"quantity": '<input type="text" id="quantity" name="quantity" class="form-control" onkeypress="return isNumber(event)" onblur="compareQuantity(this, 1)" required="required" value="" />',
}]
I managed to fix the problem I had by creating hidden input which I use to store my entered quantity and when user clicks add button,which is on the first and create my second table. I than get crap the entered value assign it to my hidden input.
<!-- part Number and Quantity Entered -->
<input type="hidden"id="quantityList" name="quantityList" class="form-control" value="" />
var quantityList = [];
$(".addLineItem").on("click", function() {
debugger;
var items = [];
var row = $(this).closest("tr").clone();
var partNumber = $(this).closest('tr').find('td:eq(0)').find('input').val();
var quantity = $(this).closest('tr').find('td:eq(4)').find('input').val();
quantityList [quantityList.length]= [quantity];
document.getElementById("quantityList").value = quantityList;
debugger;
items.push(row);
row.appendTo($("#mySecondTable"));
});

display number 2 decimals

I have this code with 3 sliders that adds up all the 3 values of the sliders and displays it on the page, I want it to display it with 2 decimals after the comma. I tried using .toFixed(2) but I don't know where to place it exactly. Here is my code :
<div class="wrapper2">
<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 />
<div id = "info"></div>
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
$('.slider').on('slide', function(slider){
var ram = $("#ram").val()*3.50;
var diskSpace = $("#diskSpace").val()*1.20;
var cpu = $("#cpu").val() * 6.30;
$("#info").html(parseInt(ram)+ parseInt(diskSpace)+ parseInt(cpu));
});
// If you want to change slider using input text
$("#inputValue").on("keyup", function() {
var val = Math.abs(parseInt(this.value, 10) || minSliderValue);
this.value = val > maxSliderValue ? maxSliderValue : val;
$('#ram','diskSpace','cpu').slider.toFixed(2)('setValue', val);
});
Jsfiddle: http://jsfiddle.net/4c2m3cup/34/
change your summing up code to the following
$('.slider').on('slide', function(slider){
var ram = $("#ram").val()*3.50;
var diskSpace = $("#diskSpace").val()*1.20;
var cpu = $("#cpu").val() * 6.30;
var totalSum=(parseFloat(ram)+ parseFloat(diskSpace)+ parseFloat(cpu)).toFixed(2);
$("#info").html(totalSum);
});
Hope it helps
You were parsing to an int. When you parse to int you lose the decimal places.
$("#info").html(parseInt(ram)+ parseInt(diskSpace)+ parseInt(cpu));
You can add them up and use x.toFixed(2). This will give you two decimal places just change the number as desired.
$("#info").html((ram + diskSpace + cpu).toFixed(2));

Total price calculator logic difficulty

I have two number inputs, what I want to do is to get dynamially the total price.
The problem is that when I decrease the number its still adding and doesn't work correctly. Actually my brain cannot imagine any way to code it correctly. Could someone give me any clue please?
<input type="number" name="open" id='open' min="0" max="20">
<input type="number" name="vip" id='vip' min="0" max="20">
<p> Total Price: <span id='doZaplaty'>0</span> EURO</p>
<script>
var vipPrice = 290;
var openPrice = 80;
var totalPrice = 0
$('#open').on("change", function() {
totalPrice = totalPrice + ($("#open").val() * openPrice);
$("#doZaplaty").html(totalPrice);
});
$('#vip').on("change", function() {
totalPrice = totalPrice + ($("#vip").val() * vipPrice);
$("#doZaplaty").html(totalPrice);
});
</script>
Because totalPrice = totalPrice + ($("#open").val() * openPrice); will add up previous result, as I commented.
However, you have 2 different total to take into account, so it's not easy to keep the state with only one total, because you need to subtract the previous result ,or calculate the change from previous value.
Instead, you can have 2 different total, like openTotal for result on #open and vipTotal on result for #vip, then you can use openTotal = ($("#open").val() * openPrice); to get the current state. And when you need to output the result, use $("#doZaplaty").html(openTotal + vipTotal); to show the final total.
var vipPrice = 290;
var openPrice = 80;
var openTotal = 0;
var vipTotal = 0;
$('#open').on("change", function() {
// As the totals are separated, we just need to get its current values computed.
openTotal = ($("#open").val() * openPrice);
$("#doZaplaty").html(openTotal + vipTotal);
});
$('#vip').on("change", function() {
vipTotal = ($("#vip").val() * vipPrice);
$("#doZaplaty").html(openTotal + vipTotal);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p> Total Price: <span id='doZaplaty'>0</span> EURO</p>
<input type="number" name="open" id='open' min="0" max="20">
<input type="number" name="vip" id='vip' min="0" max="20">
Because you always add to totalPrice. Try this instead (untested):
<script>
var totalPrice = 0
function GetTotalPrice(vipNum,openNum){
var vipPrice = 290;
var openPrice = 80;
var total = vipNum * vipPrice + openNum * openPrice;
return total;
}
$('#open').on("change", function(){
totalPrice = GetTotalPrice($("#vip").val(),$("#open").val());
$("#doZaplaty").html(totalPrice);
});
$('#vip').on("change", function(){
totalPrice = GetTotalPrice($("#vip").val(),$("#open").val());
$("#doZaplaty").html(totalPrice);
});
</script>
Please tyr by this simple way
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p> Total Price: <span id='doZaplaty'>0</span> EURO</p>
<input type="number" name="open" id='open' min="0" max="20">
<input type="number" name="vip" id='vip' min="0" max="20">
Set 2 hidden fields to store temp calculation value
<input type="hidden" name="totalPriceopenTemp" id='totalPriceopenTemp' value="0">
<input type="hidden" name="totalPricevipTemp" id='totalPricevipTemp' value="0">
<p> Total Price: <span id='doZaplaty'>0</span> EURO</p>
<script>
var vipPrice = 290;
var openPrice = 80;
var totalPrice = 0;
var totalPriceopenTemp = 0;
var totalPricevipTemp = 0;
$('#open').on("change", function() {
totalPriceopenTemp = ($("#open").val() * openPrice);
$("#totalPriceopenTemp").val(totalPriceopenTemp);
totalPrice = parseInt($("#totalPriceopenTemp").val())+parseInt($("#totalPricevipTemp").val());
$("#doZaplaty").html(totalPrice);
});
$('#vip').on("change", function() {
totalPricevipTemp = ($("#vip").val() * vipPrice);
$("#totalPricevipTemp").val(totalPricevipTemp);
totalPrice = parseInt($("#totalPriceopenTemp").val())+parseInt($("#totalPricevipTemp").val());
$("#doZaplaty").html(totalPrice);
});
</script>
I think It will work for you

Categories