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));
Related
I have written a code to calculate Burger, Coca and Salad price. The code should return a number (or a factor) based on the number or each ordered item. I can't figure out which part of the code is not right. it doesn't work when I change the number of items.
var BurgNum = document.getElementById('Bnum').value,
CocNum = document.getElementById('Cnum').value,
SalNum = document.getElementById('Snum').value,
Totalprice;
function getValue(n) {
return n >= 2 && n < 5 ? n * 0.9 : n == 0 ? 0 : n == 1 ? 1 : n - 1;
}
var XBurgNum = getValue(BurgNum);
var XCocNum = getValue(CocNum);
var XSalNum = getValue(SalNum);
Totalprice = XBurgNum * 10 + XCocNum * 5 + XSalNum * 4
document.getElementById('price').value = Totalprice;
<html>
How many Burgers you want to order? <input type="number" id="Bnum" value="0" onchange="getValue(n);"></input>
<br> How many Cocas you want to order? <input type="number" id="Cnum" value="0" onchange="getValue(n);"></input>
<br> How many Salads you want to order? <input type="number" id="Snum" value="0" onchange="getValue(n);"></input>
<br> Price: <input type="number" id="price" readonly="readonly"></input>
</html>
You are calling a function onchange which returns a value, but does nothing with it. Instead, your onchange function can get the values needed for the calculation and update the price accordingly.
var burg = document.getElementById('Bnum'),
coc = document.getElementById('Cnum'),
sal = document.getElementById('Snum'),
totalPrice = 0;
document.getElementById('price').value = totalPrice;
var updatePrice = function() {
var burgNum = burg.value,
cocNum = coc.value,
salNum = sal.value;
var xNums = [];
[burgNum, cocNum, salNum].forEach(function(n, i) {
xNums[i] = (n >= 2 && n < 5) ? n * 0.9 : n == 0 ? 0 : n == 1 ? 1 : n - 1;
});
totalPrice = xNums[0]*10 + xNums[1]*5 + xNums[2]*4;
document.getElementById('price').value = totalPrice;
}
How many Burgers do you want to order?
<input type="number" id="Bnum" value ="0" onchange="updatePrice()"/><br>
How many Cocas do you want to order?
<input type="number" id="Cnum" value ="0" onchange="updatePrice()"/><br>
How many Salads do you want to order?
<input type="number" id="Snum" value="0" onchange="updatePrice()"/><br>
Price:
<input type="number" id="price" readonly="readonly"/>
That is because you are not calling right statement on 'onchange' event. You just call the getVAlue(n) function which does nothing except return a value that you also use for
var XBurgNum = getValue(BurgNum);
var XCocNum = getValue(CocNum);
var XSalNum = getValue(SalNum);
But you are not updating the output on change event.
Try this, It will help you...
function getValue(val)
{
var BurgNum = parseInt(document.getElementById('Bnum').value);
var CocNum = parseInt(document.getElementById('Cnum').value);
var SalNum = parseInt(document.getElementById('Snum').value);
BurgNum = (BurgNum>=2 && BurgNum<5)?BurgNum*0.9:(BurgNum<2)?BurgNum:BurgNum-1;
CocNum = (CocNum>=2 && CocNum<5)?CocNum*0.9:(CocNum<2)?CocNum:CocNum-1;
SalNum = (SalNum>=2 && SalNum<5)?SalNum*0.9:(SalNum<2)?SalNum:SalNum-1;
Totalprice = BurgNum*10 + CocNum*5 + SalNum*4;
document.getElementById('price').value = (Totalprice>0 && Totalprice!=='NaN')?Totalprice:0;
}
<html>
How many Burgers you want to order? <input type="number" id="Bnum" value ="0" onChange="getValue(this.value);"></input>
<br>
How many Cocas you want to order? <input type="number" id="Cnum" value ="0" onChange="getValue(this.value);"></input>
<br>
How many Salads you want to order? <input type="number" id="Snum" value="0" onChange="getValue(this.value);"></input>
<br>
Price: <input id="price" readonly="readonly"></input>
</html>
Happy Coding...
I have the conversion math correct(looked it up here), but getting the value from the element that displays the height in cm, then parse it to ft/inch and display it on(on click) the right hand span does not work, i get a reference error(converter not defined).
I cannot figure out why it is undefined, is it because of hoisting or can the parseInt function not have the parameters as they are?
Here is the function
var displayInches = document.getElementById("heightInches");
displayInches.addEventListener("click", function() {
toFeet(converter);
});
function toFeet(converter) {
var heightOutputCM = document.getElementById("yourHeight");
var converter = parseInt(heightOutputCM.value);
var realFeet = converter * 0.3937 / 12;
var feet = Math.floor(realFeet);
var inches = Math.round((realFeet - feet) * 12);
return feet + "and" + inches;
}
Here is the link:
https://codepen.io/damianocel/pen/ZyRogX
HTML
<h1>Alcohol blood level calculator</h1>
<fieldset>
<legend>Your Indicators</legend><br>
<label for="height" class="margin">Height:</label>
<span class="leftlabel" id=""><span id="yourHeight"></span>Cm</span>
<input type="range" id="UserInputHeight" name="height" min="0" max="200" step="1" style="width: 200px">
<span id="heightInchesSpan" class="rightlabel"><span id="heightInches"></span>Ft</span>
<br>
<label for="" class="margin">Gender:</label>
<span class="leftlabel">Male</span>
<input type="range" id="salary" name="salary" min="0" max="1" style="width: 200px">
<span class="rightlabel">Female</span>
</fieldset>
JS
// get and display height
var displayHeightInput = document.getElementById("UserInputHeight");
displayHeightInput.addEventListener("input", function() {
sliderChange(this.value);
});
function sliderChange(val) {
var heightOutput = document.getElementById("yourHeight");
heightOutput.innerHTML = val;
toFeet();
return val;
}
function toFeet() {
var heightOutputCM = document.getElementById("yourHeight");
var converter = parseInt(heightOutputCM.innerHTML);
var realFeet = converter * 0.3937 / 12;
var feet = Math.floor(realFeet);
var inches = Math.round((realFeet - feet) * 12);
document.getElementById("heightInches").innerHTML=feet + "and" + inches;
return feet + " and " + inches;
}
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/
I'm working on a an input slider which uses css translate for both "-" and "+" values using a JavaScript if/else function. I'm having a little problem with the if/else statement though.
Here's a fiddle http://jsfiddle.net/cn6St/ and here's the code:
HTML
<div class="square"></div>
<span class="result-X">Transform-X:</span>
<input type="range" id="sliderX" min="0" max="100" value="50" onchange="rangevalueX.value=value"/>
<output id="rangevalueX">50</output>
JS:
var sliderx = document.getElementById("sliderX");
var box = document.querySelector('.square');
var rangevalueX = document.getElementById("rangevalueX");
sliderx.onchange = function(){
if (rangevalueX >'50') {
box.style.webkitTransform = "translateX(" + (sliderx.value) + 'px)';
rangevalueX.value = sliderx.value;
}
else if (rangevalueX <'50') {
box.style.webkitTransform = "translateX(-" + (sliderx.value) + 'px)';
rangevalueX.value = sliderx.value;
}
};
The idea is to use the value of "50" on the slider as "0" in terms of translate. If the slider value is > 50 the CSS should transform a positive value. If it's less <50 it should be negative.
Not sure what I'm doing wrong here through.
You'll want to do:
var rangevalueX = document.getElementById('rangevalueX').value;
To get the actual slider value.
I Seem to have found the issue. It was the HMTL. The value of the slider should be set to "0", while the min should be "-50" and the max value should be "50".
Final working code:
HTML:
<div class="square"></div>
<div>
<span class="result-X">Transform-X:</span>
<input type="range" id="sliderX" min="-50" max="50" value="0" onchange="rangevalueX.value=value"/>
<output id="rangevalueX">0</output>
</div>
</div>
JavaScript:
var sliderx = document.getElementById("sliderX");
var box = document.querySelector('.square');
var rangevalueX = document.getElementById("rangevalueX");
sliderx.onchange = function(){
if (rangevalueX >'50') {
box.style.webkitTransform = "translateX(" + (sliderx.value) + 'px)';
rangevalueX.value = sliderx.value;
}
else if (rangevalueX <'50') {
box.style.webkitTransform = "translateX(-" + (sliderx.value) + 'px)';
rangevalueX.value = sliderx.value;
}
};
Working fiddle http://jsfiddle.net/cn6St/2/
I am trying to make a function using jquery where i want to get the total number of input in a page with attibute value defined by me . For eg there are four input tags
<input type="hidden" class="code" barcode="567" total_quantity="3" name="product1" value="Nokia rita" class="product-10105">
<input type="hidden" class="code" barcode="567" total_quantity="3" name="product1" value="Nokia rita" class="product-10105">
<input type="hidden" class="code" barcode="567" total_quantity="3" name="product1" value="Nokia rita" class="product-10105">
<input type="hidden" class="code" barcode="200" total_quantity="3" name="product1" value="book" class="product-200">
In the above tags i want to pre define barcode number in a variable and the count the number of inputs accordingly and also get the value of total_quantity in a variable for that barcode number i provide. I made the following code to get the total inputs but its for all input and is not according to barcode i will specify .
var barcode_pd = $('input[barcode]').size();
var total_pd = $('input.code').attr("total_quantity");
var sumOfVals = 0;
$(".mn-no-cnt").each(function(){sumOfVals = sumOfVals + parseInt($(this).val(), 10);});
Using above code the ouput for count of input is 4 and i want to specify the barcode number too such as 567 so that the count could be 3 or if i use barcode number 200 then the count is 1.
I have used array to store values.
var code = [];
var count = [];
$("input.code").each(function(){
var c = $(this).attr("barcode");
if(code.indexOf(c) >= 0){
count[code.indexOf(c)] += 1;
}
else{
code.push(c);
count.push(1);
}
});
for(var i=0;i<code.length;i++){
$("body").append("<p>Barcode:"+code[i]+" Count:"+count[i]+"</p>");
}
DEMO here.
Without using jQuery:
function getCount(barcode){
var code = document.getElementsByClassName('code') ;
var length = code.length ;
var count = 0 ;
for(var i = 0 ; i < length ; i++){
if(code[i].attributes['barcode'].value == barcode) count++ ;
}
return count ;
}
// Test
alert(getCount(567)) ; // 3
alert(getCount(200)) ; // 1
Demo : http://jsfiddle.net/wz98E/
http://jsfiddle.net/A95Js/
function countBarcode(numberToFind){
var countInputs = 0;
$('input[barcode]').each(function(){
if($(this).attr("barcode") == numberToFind){
countInputs ++;
}
return countInputs;
});
}
$('#answer').html(countBarcode(567));
This is purely to count them - but combined with Hirals answer you should be able to work out how to turn his into a function. JSfiddle is above - obviously to make this useful you need to return the value not add it to a div - was just showing how to count it.
Try this. Set the barcode variable to the barcode you want to search for. I have also converted to data- attributes and have provided code to count and sum the data-total_quantity:
HTML:
<input type="hidden" class="code" data-barcode="567" data-total_quantity="3" name="product1" value="Nokia rita" id="product-10105">
<input type="hidden" class="code" data-barcode="567" data-total_quantity="3" name="product1" value="Nokia rita" id="product-10106">
<input type="hidden" class="code" data-barcode="567" data-total_quantity="3" name="product1" value="Nokia rita" id="product-10107">
<input type="hidden" class="code" data-barcode="200" data-total_quantity="3" name="product1" value="book" class="product-200">
Javascript:
$(function () {
var barcode = 567; // set to whatever you want to search for...
var sumOfVals = 0;
$("input.code[data-barcode='" + barcode + "']").each(function () {
sumOfVals += parseInt($(this).data('total_quantity'), 10);
});
alert("Length: " + $("input.code[data-barcode='" + barcode + "']").length);
alert("Sum: " + sumOfVals);
});
Fiddle:
http://jsfiddle.net/d89BR/4/
Try this :
var barcode = 123;
var $123 = $('input[data-barcode="' + barcode + '"]');
var howMany = $123.length;
var sumOfQuantities = Function('return ' + $123.map(function () {
return $(this).data('quantity');
}).get().join('+') + ';')();
var sumOfValues = Function('return ' + $123.map(function () {
return $(this).val() || '0';
}).get().join('+') + ';')();
HTML (example) :
<input data-barcode="123" data-quantity="123" value="123" />