I'm currently working on a budget software and I've come across this strange bug. First of here is my code:
<label class="label label-success">Choose your budget</label><br/><br/>
<div class="input-group-addon">€</div>
<input type="number" min="10" max="25000" maxlength="5" step="10" class="form-control" id="Input-budget" placeholder="Amount" onkeyup="this.value=this.value.replace(/[^\d]/,'')" onchange="budCalculate(this.value)">
this is the output line:
<li>
<strong>
Total cost: <span id="cost_eur">€0.00 </span> (<span id="cost_usd" class="small">$0.00</span>)
</strong>
</li>
Here is the Javascript:
function budCalculate(budget_amount) {
var budget = budget_amount;
cost_eur.innerHTML = "€"+((budget).toFixed(2);
cost_usd.innerHTML = "$"+ (budget * 1.13 ).toFixed(2);
}
It's supposed to put the value of the input on the output line.
The onkeyup is to prevent people from typing letters.
I've tried all kinds of variations and the funny thing is almost the same identical code is working on a similar looking page.
Why doesn't JavaScript put respeck on my value?
I suspect the issue is that budget is not a Number Object. this.value will pass a String Object. I would advise changing your function:
function budCalculate(budget_amount) {
var budget = 0;
console.log(typeof budget_amount);
budget = parseFloat(budget_amount);
cost_eur.innerHTML = "€" + budget.toFixed(2);
cost_usd.innerHTML = "$" + ( budget * 1.13 ).toFixed(2);
return budget;
}
You can now see what type of object is being passed. The parseFloat() should correct the issue.
Working Example: https://jsfiddle.net/Twisty/bqjg50sb/
Related
I have the following HTML that is within a form, to accept 2 numbers from two separate inputs
<input type="number" id="amount" name="amount" value="0" onchange="ltv()">
<input type="number" id="property_value" name="property_value" value="0" onchange="ltv()">
<p id="ltv"></p>
Then some JavaScript
function ltv() {
var amount = document.getElementById("amount").textContent;
var property_value = document.getElementById("property_value").textContent;
document.getElementById("ltv").innerHTML = Math.round(amount/property_value*100);
};
However after entering a number into the "amount" input the ltv element is updated with NaN which is to be expected at this stage as only the first variable in the math operation is set, however upon entering the second number and tabbing away from the input field the ltv is not updated again.
Seems like textContent isn't returning anything. Try to use .value
function ltv() {
var amount = document.getElementById("amount").value;
var property_value = document.getElementById("property_value").value;
document.getElementById("ltv").innerHTML = Math.round(amount/property_value*100);
};
For some reason in my program, the + sign adds two digits together, in my code:
numerator1 += wholenumber1 * denominator1;
If wholenumber1 is 1 and denominator1 is 4, then the numerator1 is 14... I found this out by:
console.log(numerator1);
This is using inputs with type="number", and the other parts of the equation are working just fine... But this part is essential in order for my program to run properly, and help is greatly appreciated!
Though the input type is number, the actual value is of type string. You can check this by typeof operator. So you have to use functions like parseInt() to convert the value to integer in order to perform actual arithmetic operation.
console.log(typeof(document.getElementById('num1').value));
<input type="number" id="num1" value="1"/>
Code Example:
var numerator1 = 0;
var wholenumber1, denominator1;
wholenumber1 = document.getElementById('wholenumber1').value;
denominator1 = document.getElementById('denominator1').value;
numerator1 += parseInt(wholenumber1) * parseInt(denominator1);
console.log(numerator1);
wholenumber1: <input type="number" value="1" id="wholenumber1" /> <br/>
denominator1: <input type="number" value="4" id="denominator1" />
You need to convert the input into integers for this to work.
You can use use numerator1 += parseInt(wholenumber1) * parseInt(denominator1);
Refer to This for more
With the following script, i am trying to validate whether the refund amount wlt_ln_refund_amt is greater than the balance amount wlt_ln_bal using keyup function.
In my html read only field wlt_ln_bal (field type = number) i have a an amount 222.00
the other field wlt_ln_refund_amt (field type = number)
The testcase
for the value 3 the system is throwing an error message like "Refund amount Rs.3 is greater than Balance Rs.222.
for the values 1, 2 or 2000 the system is not throwing any errors
Here is my html code:
<form id="lnrefund" name="lnrefund"
method="post" role="form"
class="form-horizontal"
action="<?php echo $_SERVER['PHP_SELF']; ?>"
onsubmit="return (checkform() && confirm_update())">
<div class="form-group">
<label class="col-md-2 col-xs-12 control-label">Loan Balance</label>
<div class="col-md-3 col-xs-12">
<input id="wlt_ln_bal" Name="wlt_ln_bal"
type="number"value ="<?php echo $bal ?>"
class="form-control required" readonly/>
<span class="help-block">Required</span>
</div>
</div>
<label class="col-md-2 col-xs-12 control-label">Refund Amount</label>
<div class="col-md-3 col-xs-12">
<input id="wlt_ln_refund_amt"
Name="wlt_ln_refund_amt"type="number" step="0.01"
class="form-control" required/>
<span class="help-block">Required</span>
</div>
</form>
And this is the javascript
<script type="text/javascript">
$(function(){
$("#wlt_ln_refund_amt").keyup(function () {
var ref = document.lnrefund.wlt_ln_refund_amt.value;
var bal = document.lnrefund.wlt_ln_bal.value;
if (ref>bal)
{
alert('Refund amount Rs.'+ref+ '\nis greater than Available Balance Rs.'+bal)
return true;
}
});
});
</script>
It looks like the variables are being compared as strings (i.e. alphabetically) you should try something like
var ref = parseInt(document.lnrefund.wlt_ln_refund_amt.value);
var bal = parseInt(document.lnrefund.wlt_ln_bal.value);
or maybe
var ref = parseFloat(document.lnrefund.wlt_ln_refund_amt.value);
var bal = parseFloat(document.lnrefund.wlt_ln_bal.value);
if you're expectiong decimals
Since you asked for suggestions... :P
I'd use jQuery to get the values of the two inputs. You're already using jQuery for the document ready function, so why not use:
var $refund = $('#wlt_ln_refund_amt'),
$balance = $('#wlt_ln_bal.value');
What you're doing works fine - as long as the structure of your HTML never changes. Using jQuery like this means you don't have to worry about ever wrapping your inputs in a containing DIV or changing the form to a popup dialog later on.
Next, I wouldn't use the keyup event, I'd use the blur event. Perhaps your use case requires the check after every keystroke, but that usually annoys users. If you bind to the blur instead of the keyup, your user will have an opportunity to correct a mistake during typing before getting yelled at by your function.
$refund.on('blur', function(){
var refAmount = parseInt($refund.val()),
balAmount = $balance.val() * 1;
if (refAmount > balAmount)
{
alert('Refund amount Rs.' +
refAmount +
'\nis greater than Available Balance Rs.' +
balAmount);
$refund.focus();
}
});
As someone else suggested, make sure the values you're comparing are numeric. You can use the parseInt as suggested (the preferred way) or force type conversion by multiplying the value by 1. Either way will result in a NaN (not a number) if the user enters something other than numbers.
After the alert, I'd return focus back to the refund amount to give the user another shot at the entry.
As a final suggestion, I'd recommend using readable variable names. Perhaps you shortened them just for this question, but descriptive variable names are much easier to deal with than obscure abbreviations.
Good luck!
I feel like I'm a novice again. I thought I was long past these problems. below is a simple script with two function neither of which work. What am I missing. Any help appreciated.
function calculator() {
var bee = document.getElementById("beerPerc").value;
var win = document.getElementById("winePerc").value;
var liq = 100 - (bee + win);
document.getElementById("liquorPerc").value = liq;
}
function calculator2() {
document.getElementById("liquorPerc").value = parseInt(100 - (document.getElementById("beerPerc").value + document.getElementById("winePerc").value))
}
<div id="calcArea">
<div>
<input type="number" id="beerPerc" value="50" onkeyup="calculator2()"> % of Beer Drinkers<br>
<input type="number" id="winePerc" value="30" onkeyup="calculator2()"> % of Wine Drinkers<br>
<input type="number" id="liquorPerc" onkeyup="calculator2()"> % of Liquor Drinkers<br>
</div>
</div>
Two things:
Case is significant. If you declare the variable bee, you can't read it with Bee.
.value is always a string. You need to convert the strings to numbers:
var bee = Number(document.getElementById("beerPerc").value);
If you don't do this, + will perform string concatenation, not addition.
You don't need to call parseInt() on the result of a numeric calculation, that's always a number.
function calculator2() {
document.getElementById("liquorPerc").value = 100 - (parseInt(document.getElementById("beerPerc").value, 10) + parseInt(document.getElementById("winePerc").value, 10)))
}
http://jsfiddle.net/beY6d/
I want to make a simple HTML+JS page that basically gives the user 4 text fields to write the name of some product and an extra field that displays the remaining credit in the 5th text field.
<input type="text" value="0" class="product" id="shirtItems"/><br>
<input type="text" value="0" class="product" id="pantsItems"/><br>
<input type="text" value="0" class="product" id="hatItems"/><br>
<input type="text" value="0" class="product" id="accesoryItems"/><br>
<input type="text" value="100" id="credit" disabled/>
var shirt= document.getElementById("shirtItems");
var pants= document.getElementById("pantsItems");
var hat= document.getElementById("hatItems");
var accesory= document.getElementById("accesoryItems");
var remainingDosh = document.getElementById("credit");
remainingDosh.value = 100;
There must be a .onblur (or .onfocus) event to make the "credit" field display 100 minus the sum of every other item.
Also, the price of the item must change depending on the color/type of item. Something like:
shirt.onblur = function(){
if (shirt.value == "Blue") {remainingDosh.value = remainingDosh-25}
if (shirt.value == "Red") {remainingDosh.value = remainingDosh-20;}
};
If you do typeof remainingDosh.value, you'll see that it logs string. This means you'll have to convert the string to a number if you don't want to risk having NaN show up on your page.
Convert it with parseInt() like so:
var remainingDosh.value = parseInt(remainingDosh,10)-25;
The second parameter, 10 is the radix, which in this case is decimal (though it defaults to decimal if left out I believe).
And the issue in question, as pointed out, is you're trying to do math on the element remainingDosh instead of using it's value.
Oh, and protip: instead of shirt.value, you can use this.value since the event comes from said element.
you're using remainingDosh instead of remainingDosh.value when you do your subtraction.