I'm creating a script for percentage calculation on my e-commerce, but I have a problem.
I want price update in real time as I write the percentage in the field.
So I made this:
<input type="text" name="cost" onchange="disc()">
<input type="text" name="discount" id="prized" onchange="updateInput()">
<input type="text" name="price" value="">
<script>
function updateInput(){
var discount = document.getElementsByName("discount")[0].value;
var cost = document.getElementsByName("cost")[0].value;
document.getElementsByName("price")[0].value = cost - (cost * (discount / 100));
}
function disc(){
if($("#prized").val().length > 1) {
var discount = document.getElementsByName("discount")[0].value;
var cost = document.getElementsByName("cost")[0].value;
document.getElementsByName("price")[0].value = cost - (cost * (discount / 100));
}
}
<script>
But it does not work as I would like...
It does not update in real time, for "onchange".
So I did some research, and I found an interesting function: .keydown()
I have no idea how to use it in my script.
Someone can help me reach my goal?
Changing onchange by oninput should give you de behaviour you are looking for, the following snippet works for me:
function updateInput() {
var discount = document.getElementsByName("discount")[0].value;
var cost = document.getElementsByName("cost")[0].value;
document.getElementsByName("price")[0].value = cost - (cost * (discount / 100));
}
function disc() {
console.log(document.getElementsByName("discount")[0].value);
if($("#prized").val().length > 1) {
var discount = document.getElementsByName("discount")[0].value;
var cost = document.getElementsByName("cost")[0].value;
document.getElementsByName("price")[0].value = cost - (cost * (discount / 100));
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" name="cost" oninput="disc()"> <br><br>
<input type="text" name="discount" id="prized" oninput="updateInput()">
<input type="text" name="price" value="">
Couple of things: There's no need to use getElementBy* when using jQuery, there's no need to write the same function twice.
On input (rather than change or keyup) of both fields, run the function
$(function(){
$('#prized, #cost').on('input', function(){
var discount = $('#prized').val();
var cost = $('#cost').val();
var price = cost - (cost * (discount / 100));
$('#price').val(price);
})
});
https://jsfiddle.net/popnoodles/npgvmLkc/2/
I see 2 errors here:
First, you are not converting the values of the input fields to numbers; use parseInt() for this.
Second, declare your number inputs as such using ´type="number"´. This increases usability, as you will see.
Answer to your question:
If you use parseInt() in updateInput() and use onkeyup="updateInput" (or even better onkeypress="updateInput()" this should work. See this jsfiddle: http://jsfiddle.net/da5d92bk/
$("input[name='discount']").bind('input propertychange', function() {
//do your update here
}
Just try to use keyup listener like below.
$(document).ready(function() {
var copyField = $('#copyvalue'); //field where you want to copy
$('input[type="text"]').keyup(function() {
if($(this).val() != '') {
copyField.val($(this).val());
}
});
});
$('#idofelement').keydown(function() {
...
});
Related
I have a discount jquery calculator plugin.It is working. But percentage is not working with decimal values like Eg: 5.45%, 10.50% , 15.70%, 20.75% etc.. I created a Codepen project for it. Please check this Codepen link https://codepen.io/coderco/pen/gOeReMQ . Here is my codes. Please help me..
HTML
<input type="text" id="Amount" value="">
<input type="text" value="10.45" id="Discount">
<input type="text" id="Result">
Script
$(document).on("change keyup blur", "#Discount", function() {
var main = $('#Amount').val();
var disc = $('#Discount').val();
var dec = (disc / 100).toFixed(2); //its convert 10 into 0.10
var mult = main * dec; // gives the value for subtract from main value
var discont = main - mult;
$('#Result').val(discont);
});
It's because of toFixed(2). When you divide the value by 100 then there are 4 decimal places.
For example:
Amount = 100, Discount = 10.45
dec = (10.45/100) = 0.1045 (Calling toFixed(2) changes it to 0.10 that means 10 instead of 10.45).
In my suggestion add toFixed(2) to the final answer (discount), Instead of while calculating.
I get the sum of ua and ub and display on tu textbox. I multiplied the ua
and ga textbox and display on uu textbox as well as the ub ang gb . Get
the sum of uu and a and display on tt textbox. I want to get the quotient
of tt and tu and display on gpa textbox but it doesnt work. Please help.
Thanks in advance.
function sum(){
var ua = document.getElementById('ua').value;
var ub = document.getElementById('ub').value;
var result = parseInt(ua) + parseInt(ub);
if (!isNaN(result)) {
document.getElementById('tu').value = result;
document.getElementById('tu').dispatchEvent(new Event('change'));
}
}
function suma(){
var ua = document.getElementById('ua').value;
var ga = document.getElementById('ga').value;
var result = parseInt(ua) * parseInt(ga);
if (!isNaN(result)) {
document.getElementById('uu').value = result;
document.getElementById('uu').dispatchEvent(new Event('change'));
}
}
function sumb(){
var ub = document.getElementById('ub').value;
var gb = document.getElementById('gb').value;
var result = parseInt(ub) * parseInt(gb);
if (!isNaN(result)) {
document.getElementById('a').value = result;
document.getElementById('a').dispatchEvent(new Event('change'));
}
}
function s(){
var uu = document.getElementById('uu').value;
var a = document.getElementById('a').value;
var result = parseInt(uu) + parseInt(a);
if (!isNaN(result)) {
document.getElementById('tt').value = result;
document.getElementById('tt').dispatchEvent(new Event('change'));
}
}
function g(){
var tt = document.getElementById('tt').value;
var tu = document.getElementById('tu').value;
var result = parseFloat(tt) / parseFloat(tu);
if (!isNaN(result)) {
document.getElementById('gpa').value = result;
}
}
<input type="text" id="ua" name="ua" size="7" onkeyup="sum();">
<input type="text" id="ga" name="ga" size="7" onkeyup="suma();">
<input type="text" id="uu" name="uu" size="7" onchange="s();"/>
<input type="text" id="ub" name="ub" size="7" onkeyup="sum();">
<input type="text" id="ga" name="ga" size="7" onkeyup="sumb();">
<input type="text" id="a" name="a" size="7" onchange="s();"/>
<input type="text" id="tu" name="tu" onchange="g();"/>
<input type="text" id="tt" name="tt" onchange="g();"/>
<label>GPA</label>
<input type="text" id="gpa" />
As far as I can tell, everything in your code works (after your edit), except that you want to get the element with the ID gb in the function sumb, but the element doesn't exist. As you have it now, your code displays the result of the value of tt (second in the HTML) divided by the value of tu (first in the HTML).
That said, I'm still not sure what you mean when you say "it's not working". The only thing I could think of is that you have to take away the focus from the tu or tt input element in order to make the gpa element display the result, because you used onchange instead of onkeyup.
As others have pointed out and as I also want to emphasize is that you should try to give your variables meaningful names. When you look at your code in three years, do you think you will still know what "gpa" and "uu" is?
In the following snippet, I only copied the <input>s that are relevant for the division. I use addEventListener instead of inline event listeners (onkeyup="sumb();") and made it more readable:
var dividendElement = document.getElementById('dividend');
var divisorElement = document.getElementById('divisor');
var resultElement = document.getElementById('result');
function updateQuotient () {
var result = parseFloat(dividendElement.value) / parseFloat(divisorElement.value);
if (!isNaN(result)) {
resultElement.value = result;
}
}
dividendElement.addEventListener('keyup', updateQuotient);
divisorElement.addEventListener('keyup', updateQuotient);
<input type="text" id="dividend">
/
<input type="text" id="divisor"> <!-- <input> elements don't need a closing tag! -->
=
<input type="text" id="result">
So the user wants to buy some potato. He can either enter the amount of potato in kilograms and get total price in dollars, or he can do the reverse - enter dollars and get kilograms of potato. So there's 2 input fields.
Requirements: values must update immediately after typing. Entering value in one field updates the other, and vice versa. Kilograms must stay whole, with one exception - when user enters not whole weight himself.
Price is stored internally in cents. Price is shown to the user as dollars per 1000 kilogram. Amount in kilograms is always integer.
Here is my code:
var ViewModel = function () {
var self = this;
this.totalPrice = ko.observable();
this.pricePerKg = ko.observable(999);
this.potatoWeight = ko.computed({
read: function () {
var totalPrice = self.totalPrice();
var potatoWeight = (totalPrice * 100) / self.pricePerKg() * 1000;
return Math.round(potatoWeight);
},
write: function (potatoWeight) {
var totalPrice = (potatoWeight * self.pricePerKg()) / 100 / 1000;
self.totalPrice(totalPrice.toFixed(2));
}
});
};
ko.applyBindings(new ViewModel());
HTML:
<label for="potato">Potato, kg</label>
<input type="text" id="potato" data-bind="textInput: potatoWeight">
<label for="priceTotal">Price total, $</label>
<input type="text" id="priceTotal" data-bind="textInput: totalPrice">
<div> Price per 1000 kilogram:
<span data-bind="text: (pricePerKg() / 100).toFixed(2)">
</span>$
Jsfiddle: https://jsfiddle.net/9td7seyv/13/
Problem : when you type value in "potato weight" it updates not only value in dollars, but also itself. Because of rounding it leads to inconsistencies. Go to jsfiddle above and try to type 500 in weight field. It turns itself to 501 the moment you enter the last zero.
So is there a way to stop the field updating itself, or probably some other approach to this problem is needed?
For this case, the most straight forward way I can think of is to keep a copy of the value entered by the user after any calculation ... like in the code below.
var ViewModel = function () {
var self = this;
this.totalPrice = ko.observable();
this.pricePerKg = ko.observable(999);
this.weight=ko.observable();
this.potatoWeight = ko.computed({
read: function () {
return self.weight();
},
write: function (potatoWeight) {
var totalPrice = (potatoWeight * self.pricePerKg()) / 100 / 1000;
self.totalPrice(totalPrice.toFixed(2));
self.weight(potatoWeight);
}
});
};
ko.applyBindings(new ViewModel());
https://jsfiddle.net/9td7seyv/16/
update :
For both values
https://jsfiddle.net/9td7seyv/19/
I'm trying to make a really simple calculator for my website.
Basically, I want people to be able to put in their weight into a text box, click "Calculate Dose" and then the script multiplies their weight by a number that I will set myself for each page.
Here is what I have right now. Not only does it not work, but it also stops one of my ads from displaying:
<div>
<input id="inputweight" type="text" />
<input type="button" value="Calculate Dose" onClick="calculate()">
<input id="result" />
</div>
<script>
function calculate() {
var weight = document.getElementById('inputweight').value;
var result = document.getElementById('result');
var dosage = weight.value * 1;
result.value = dosage;
}
</script>
What's wrong with it?
You are missing closing tag /> in your button
<input type="button" value="Calculate Dose" onClick="calculate()"/>
You already stored weight value
var weight = document.getElementById('inputweight').value;
So you dont need this var dosage = weight.value * 1;
So use var dosage = weight * 1;
function calculate() {
var weight = document.getElementById('inputweight').value;
var result = document.getElementById('result');
var dosage = weight * 1;
result.value = dosage;
}
this line:
var weight = document.getElementById('inputweight').value;
and this:
var dosage = weight.value * 1;
do not work together well. You are retrieving the value, then the value of that... which cannot work.
So, replace the second line with:
var dosage = weight * 1;
Besides: You should check the console for errors, it should show up there.
I assume (or, guess, more correctly) that the ad that is no longer working stops because the javascript execution is typically terminated after an error.
Just update this line (remove the value attribute which is already extracted above):
var dosage = * 1;
This will work but you might also want to add this for increased type safety (it parses weight as a number):
var dosage = parseInt(weight, 10) * 1;
In your code block you are missing a closing / at the end of the second input statement. Which should be giving you an issue in your html.
<input type="button" value="Calculate Dose" onClick="calculate()"/>
You also don't need weight.value again in the third line of your function. Instead it should be:
var dosage = weight * 1;
Fiddle demonstrating your example modified to work:
http://jsfiddle.net/x38ommxs/
function calculate() {
var weight = document.getElementById('inputweight').value;
var result = document.getElementById('result');
var dosage = weight * 1;
result.value = dosage;
}
<div>
<input id="inputweight" type="text" />
<input type="button" value="Calculate Dose" onClick="calculate()" />
<input id="result" />
</div>
Added missing closing tag on button
Changed dosage to multiply the value stored in weight by one.
I apologize in advance for what I assume is a very basic question, but I am very new to scripting and would like to ask for some advice on a problem I am having.
Essentially I am creating a website that should sum the dollar amounts of two fields based on hours worked and return a total dollar amount. One of the fields has a fixed dollar amount and the other is a variable.
As far as I can tell the code should be working, but the field that should be user generated (esceptionalRate) seems to calculate correctly only after a page refresh, and then only on firefox... instead of automatically updating the total value when a change is made to the user field
code as follows:
<head>
</head>
<body>
<script>
$(document).ready(function () {
var standardRate = 110;
var exceptionalRate = $("#ex_rate").val();
var standardEntry = 0;
var exceptionalEntry = 0;
var totalVal = 0;
$("#Standard").on("change",function(){
standardEntry = $(this).val() * standardRate;
totalVal = standardEntry + exceptionalEntry;
$("#Amount").val(totalVal);
});
$("#Exceptional").on("change",function(){
exceptionalEntry = $(this).val() * exceptionalRate;
totalVal = standardEntry + exceptionalEntry ;
$("#Amount").val(totalVal);
});
</script>
and here's the HTML side:
<input name="Standard" type="number" step="any" value="0" id="Standard" size="10" />
<input type="text" size="10" name="ex_rate" id="ex_rate" />
<input name="Exceptional" type="number" step="any" value="0" id="Exceptional" size="10" />
<td valign="top" nowrap="nowrap"><font size="2">Total Amount Requested </font></td>
<td><input name="Amount" type="text" id="Amount" size="35"/></td>
thanks in advance for all your wisdom and knowledge.
You have forgotten to close the $(document).ready function
Try:
$(document).on("change", "#Standard", function(){
And:
$(document).on("change", "#Exceptional", function(){
The problem is that your exceptionalRate variable is out of the scope of your calculation, and only gets set to the initial value upon the page loading. You need to move it within the change handler:
$("#Exceptional").on("change",function(){
exceptionalRate = $("#ex_rate").val();
exceptionalEntry = $(this).val() * exceptionalRate;
totalVal = standardEntry + exceptionalEntry ;
$("#Amount").val(totalVal);
});