replace characters in price calculation JS - javascript

I'm creating a script for percentage calculation on my e-commerce, but I have a problem.
If i use use characters such as: ", . %" the price value says "NaN".
So I made this:
<input type="text" name="cost" onkeyup="disc()"> <br><br>
<input type="text" name="discount" id="prized" onkeyup="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>
How can I replace the characters when they are inserted on cost value or discount value?
I did some research, and I found an interesting function: .replace
I have no idea how to use it in my script.
Someone can help me reach my goal?

You should have to replace special characters , and & like this
var price = $(".price").val().replace(/,/g, "").replace("%", "")
This replace(/,/g, "") will replace multiple replace of comma ,
Ex. 1,00,000 be 100000

Why not validate your user input prior to calling your function? create a regex to only allow the characters you want. As it is your user can input any character they want in the input box. Probably a good idea to limit that.

I don't know whether this is the requirement, any way replace work like below,
var test = "90.56%";
test = test.replace(/[.%]/g, "");
//test will be "9056"

Related

Javascript calculation from form data returns NaN

I'm fairly new to JS and I think there's a problem with my code in the parts where I'm using Javascript for arithmetic. If someone could show me where I went wrong I'd be very grateful! Currently, everything works except it returns NaN when the calculate button is clicked.
HTML:
<form>
AGE:<br><input id="Age" data-wrapper-class="inputBox" type="text" name="Age"><br>
</form>
<form>
HEIGHT (FEET):<br><input id="Feet" data-wrapper-class="inputBox" type="text" name="Feet"><br>
</form>
<form>
HEIGHT (INCHES):<br><input id="Inches" data-wrapper-class="inputBox" type="text" name="Inches"><br>
</form>
<form>
WEIGHT (POUNDS):<input id="Pounds" data-wrapper-class="inputBox" type="text" name="Pounds"><br>
</form>
<button id="calcButton" class="ui-btn ui-btn-b">Calculate BMR</button>
</div>
<div id="resultsInfo">
<p id="results"></p>
</div>
Javascript / jQuery:
$("#calcButton").click(function() {
var age = document.forms["Age"];
var feet = document.forms["Feet"];
var inches = document.forms["Inches"];
var wip = document.forms["Pounds"];
var feetInches = feet * 12;
var heightInches = feetInches + inches;
var weightMen = 6.23 * wip;
var heightMen = 12.7 * heightInches;
var ageMen = 6.8 * age;
var one = 66 + weightMen;
var two = one + heightMen;
var menBMR = two - ageMen;
$("#Calculator").hide();
parseFloat(document.getElementById("results").innerHTML = menBMR);
$("#resultsInfo").show();
});
As Jaromanda mentioned, you need to ensure the values are actually a Number value. Once they're a number type then you can do arithmetic operations on them. Here's why this matters:
var str = "12" // Number value
var num = 12 // String value
console.log(str * 2) // 1212
console.log(num * 2) // 24
In your code example, it looks as if you used inputs that are gathering the type="text" which means the values that you get from it would give you a String value. You can convert them to a number using parseInt or parseFloat, or you can change the HTML input type to type="number", I believe.

Through javascript decrease amount in a box and increment the same value decrease to another box dynamically

Here is a sample idea.
Amount - discount = amount paid by the customer.
But the customer pay less and the box due need to be increment dynamically.
Can anyone help me please?
Here is a simple version of what I believe you're asking for:
HTML
Price: <input type="text" id="tb-price" />
Discount (%) <input type="text" id="tb-discount" />
Total: <span id="lbl-total" />
Javascript (jQuery required)
$(function(){
// vars
var $tbPrice = $('#tb-price');
var $tbDisc = $('#tb-discount');
var $lblTotal = $('#lbl-total');
// events
$tbPrice.on('input', calc);
$tbDisc.on('input', calc);
// calculation
function calc(){
var x = $tbPrice.val() * ($tbDisc.val() / 100);
var y = $tbPrice.val() - x;
$lblTotal.html(y);
}
});
Example: http://jsfiddle.net/zkhx1z1d/
Do note that there is no validation here and assumes that the user input is clean. Also this should only be used to show the user what they expect to pay, all calculations should be done/verified by the server as suggested by AlienWebguy

Strange jquery bug in simple code

I have a simple html code with form:
<span class="price"></span>
Enter amount:
<input type="text" class="form-control amount" name="amount" value="500">
<!--Next input fields are hidden by Bootstrap class "hide"-->
<input type="text" name="minimal-amount" class="hide minimal-amount" value="500">
<input type="text" name="oneprice" class="hide oneprice" value="0.20">
<script>
$(".amount").on("change", function(){
var am = $(".amount").val();
var min = $(".minimal-amount").val()
if(am<min){
$(".amount").val($(".minimal-amount").val());
}else{
var am = $(".amount").val();
var oneP = $(".oneprice").val();
var finalPrice = am*oneP;
$(".price").html(finalPrice);
}
});
</script>
Idea of this code is very simple. When user put in amount field digits, my script should check, if that, what user put is smaller than minimum available value in minimal-amount field, script changes value of amount field to default minimal-amount.
But the problem is, that id I just add 0 in amount field (and it's value become 5000) everything is ok, but when I changes value of amount field to 1000, script changes value of amount field to default, as if it smaller them minimul-amount.
What I do wrong, and how can I fix this problem?
P.S. Example of this code you can find here - http://friendfi.me/tests/amount.php
You should parse the value before use. Because .val() will return only string type.
$(".amount").on("change", function(){
var am = parseFloat($(".amount").val());
var min = parseFloat($(".minimal-amount").val());
if(am<min){
$(".amount").val($(".minimal-amount").val());
}else{
var am = $(".amount").val();
var oneP = $(".oneprice").val();
var finalPrice = am*oneP;
$(".price").html(finalPrice);
}
});
There are a lot of gotchas in that code. Here is a working JSBin: http://jsbin.com/qilob/2/edit?html,js,output
Highlights
You need the DOM to be initialized before you can work with it.
Wrapping this in a function passed to jQuery will make it wait till
the page finishes loading before manipulating it.
$(function() { ... });
Use cached values since the elements are not going to change much.
This saves the need to parse the selectors multiple times. It also saves
on typing and readability.
var $amount = $("#amount");
var $minimalAmount = $("#minimal-amount");
var $onePrice = $("#oneprice");
var $finalPrice = $("#price");
When parsing a string to an Int you need to use parseInt
var amount = parseInt($amount.val(), 10);
Conversely when parsing a string to a Float you need to use parseFloat
var price = parseFloat($onePrice.val());
JavaScript can not handle float based arithmetic well.
rounding errors are bad especially when dealing with money we need
to move the decimal place to prevent rounding errors in the more significant
parts of the price value.
var total = (amount * (price * 100)) / 100;
See it in action in the JSBin.

javascript calculation field comparison algorithm

Good day,
I have 3 text fields for input.
TotalWeight
CustomUnitWeight
CustomsNumberOfUnit
There should be a validation to make sure TotalCustomWeight matches TotalWeight (neither higher nor lower).
I started playing around trying to construct a function for validating this no luck and looking for assistance
Scenario :
User input total weight of pkg at 30, then put number of custom unit at 2 and the weight at 10. On click the function calculate 2 * 10 = 20 and look at the total weight 30 and compare the total custom weight. In this case 20 does not equal to 30 therfore throw error message.
HTML
<input type="text" name="TotalWeight" id="TotalWeight" />
<input type="text" name="customsNumberOfUnitsUSA" id="CustomsNumberOfUnits" />
<input type="text" name="CustomsUnitWeight" id="CustomsUnitWeight" onChange="ChkWeight();" />
JAVASCRIPT
$(function(ChkWeight){
$('#CustomsUnitWeight').click(function() {
var TotalWeight = document.getElementById('TotalWeight');
var CustomUnitWeight = document.getElementById('CustomsUnitWeight');
var CustomsNumberOfUnit = document.getElementById('CustomsNumberOfUnits');
var TotalCustomWeight = CustomUnitWeight * CustomsNumberOfUnit;
if (TotalWeight != TotalCustomWeight) {
error message "pkg weight does not match total custom weight"
}
});
});
Well everything else is fine in your code just needs to put .value to get value from your input fields and converting string (simple text) to Float type and then calculate and show alert like
<body>
<input type="text" name="TotalWeight" id="TotalWeight" />
<input type="text" name="customsNumberOfUnits" id="CustomsNumberOfUnits"/>
<input type="text" name="CustomsUnitWeight" id="CustomsUnitWeight" onblur="CheckWeight()" />
//I have changed the event as onblur and calling CheckWeight() function defined in javascript below.
</body>
<script type="text/javascrit">
function CheckWeight()
{
var TotalWeight = document.getElementById('TotalWeight').value;
var CustomUnitWeight = document.getElementById('CustomsUnitWeight').value;
var CustomsNumberOfUnit = document.getElementById('CustomsNumberOfUnits').value;
//parsing text value to Float type for multipication
var TotalCustomWeight = parseFloat(CustomUnitWeight) * parseFloat(CustomsNumberOfUnit);
if (TotalWeight != TotalCustomWeight)
{
alert("pkg weight does not match total custom weight");
}
}
</script
and Off course you must need to validate for value to be number before calculation. This works perfect.

Why can't I set my input field with MooTools?

Ive got a document and when the user enters something into one input I need to show a response in a second input box. I can get the user given value, i can process it, but when I try to set the second input box with the result I get the error $.field is null. Here is the code:
$('places').addEvent('keyup', function(){
var places = $('places').value;
alert("PLACE: "+places);
var price = values[places];
var nights = $('nights').value.toInt();
alert("NIGHTS: "+nights);
var total = price * nights;
alert("TOTAL: "+total);
$('pricepernight').set('text', total);
$('pricetotal').set('text', total - ((total / 100) * 21));
});
So I get the place value. I pull the price of the place out of an assoc array. I then multiple that price by the amount of nights field in by the user and this is then my total amount. It is this amount that I cannot set to. Note that the alert shows the correct amount.
and the html looks like this
<div class='block'>
<input type="text" id="places" />
</div>
<div class='block'>
<label for="nachten">Aantal nachten</label>
<input type="text" id="nights" />
</div>
<div class='block long'>
<span class='label'>Prijs per slaapplaats per nacht</span>
<input type="text" class='resultfield' id='pricepernight' />
</div>
<div class='block last'>
<span class='label'>Totaalprijs excl. btw</span>
<input type="text" class='resultfield' id='pricetotal'/>
</div>
Firebug responds:
String contains an invalid character
[Break On This Error]
...x:\'4W\',3X:18.1l,al:18.1l,1Q:18.1l,as:18.1l,8S:18.1l,1F:O,3E:{x:\'1u\',y:\'1o\'...
Any ideas/suggestions anyone? Thank you in advance!
right. you seem to have used a mix of mootools and jquery code.
$('nights').addEvent('keyup', function(){
var places = $('places').value;
var price = values[places];
var nights = $('nights').value;
var total = price * nights;
alert(total);
$('#pricepernight').val(total);
//$('#pricetotal').val(total - ((total / 100) * 21));
});
in mootools 1.2+, this should be:
$('nights').addEvent('keyup', function(){
var places = $('places').get('value');
var price = values[places];
var nights = $('nights').get('value');
var total = price * nights;
alert(total);
$('pricepernight').set('value', total);
//$('#pricetotal').val(total - ((total / 100) * 21));
});
there's an implied global array values. also, this is not very safe as nights may not be integer.
the point is. #id -> id and .val() -> set('value', 'newvalue') - or .get('value')
There are couple of minor mistakes here.
First, you should use # sign to select based on your id attributes
like places and nights
Check http://api.jquery.com/id-selector/
Second, use val() to read the value from the html controls rather
than value
Check http://api.jquery.com/val/
try this
$('#nights').keyup(function(){
var places = $('#places').val();
var price = values[places];
var nights = $('#nights').val();
var total = parseInt(price) * parseInt(nights);
alert(total);
$('#pricepernight').val(total);
//$('#pricetotal').val(total - ((total / 100) * 21));
});
and what is values[places]?

Categories