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]?
Related
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.
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"
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
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.
My HTML is a simple entry form like this:
<div id="taxCalc">
<label for="subtotal">Subtotal:</label>
<input type="text" id="subtotal" >
<span id="subtotal_message">Enter order subtotal</span><br />
<label for="tax_rate">Tax Rate:</label>
<input type="text" id="tax_rate" >
<span id="tax_rate_message">Enter sales tax rate (99.9)</span><br />
<label for="sales_tax">Sales Tax:</label>
<input type="text" id="sales_tax" disabled ><br />
<label for="total">Total:</label>
<input type="text" id="total" disabled ><br />
<label> </label>
<input type="button" id="calculate" value="Calculate" onclick="calculate_click()">
<input type="button" id="clear" value="Clear" onclick="clear_click()">
And my JS is 2 simple functions...
var subtotal, taxRate, salesTax, total;
function setValues() {
subtotal = document.getElementById("subtotal").value;
taxRate = document.getElementById("tax_rate").value;
salesTax = document.getElementById("sales_tax").value;
total = document.getElementById("total").value;
}
function calculate_click() {
setValues();
salesTax = subtotal * taxRate / 100;
total = subtotal + salesTax;
}
I have included a JS Fiddle link for more information as well: http://jsfiddle.net/tjhillard/nkHxe/1/
I want the sales tax and the total to display inside the appropriate fields when the "Calculate" button is clicked.
Thank you in advance for your help!
you just need to update the values back:
change this:
function calculate_click() {
setValues();
salesTax = subtotal * taxRate / 100;
total = subtotal + salesTax;
}
into:
function calculate_click() {
setValues();
salesTax = (subtotal * taxRate) / 100;
total = subtotal + salesTax;
// place the value in the form
document.getElementById("sales_tax").value = salesTax;
document.getElementById("total").value = total;
}
updated version of your code: http://jsfiddle.net/nkHxe/4/
It should be in the following way:
function calculate_click() {
setValues();
salesTax = subtotal * taxRate / 100;
total = subtotal + salesTax;
document.getElementById("sales_tax").value = salesTax;
document.getElementById("total").value = total;
}
http://jsfiddle.net/nkHxe/5/
P.S
Keep in mind that your code is bad-organized ))
1) You don't write back the values. Maxim and Balexandre already showed how.
2) total is a concatenation of a string with a number which leads to a string again. This has not been solved by Maxim and Balexandre.
By directly reading from the input field, you get strings back. So, parse them first into numbers. Example:
parseInt(document.getElementById("subtotal").value)
In your code, you have the issue when calculating total as explained above. The issue does not occur for salesTax because the strings are automatically converted thanks to the math operations you apply.
Hope this helps.
Updated, Fully Working, total code Fixed where Integers were Passed (Concatenated) as Strings.
Code added,
subtotal = parseInt(document.getElementById("subtotal").value)
total = parseInt(document.getElementById("total").value)
Link,
http://jsfiddle.net/nkHxe/150/
Thanks to TJH, Balexandre, Maxim and Patrick :)