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
Related
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/
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.
<SCRIPT Language = JavaScript>
function calculate() {
a = 12
b = eval(document.form.number.value)
c = 5J7S
d = (a + b + c)
alert(d)
}
</SCRIPT>
<FORM NAME = form>
Phone: <INPUT TYPE = text SIZE = 3 value ="">
-
<INPUT TYPE = text name = number SIZE = 3 value ="">
-
<INPUT TYPE = text SIZE = 4 value ="">
<P>
<Input Type = Button NAME = b1 VALUE = "Grab Code" onClick = calculate()
</FORM>
5JG7S (Fixed Value)
5+7=12 (Added both numbers from Fixed Value)
Phone number 123-456-7890
4+5+6=15 (Prefix added together)
12+15=27 (Added numbers from the Fixed Value and the numbers that were added from the prefix)
27+5JG7S=275JG7S (Those numbers were added to the beginning of the orginal Fixed Value)
Now this Script that I have:
a is the added numbers from the Fixed Value
b is the input from the form(phone number)
c is the Fixed Value
d is adding each one up so they will display the code as an alert.
Now, if I take out c and just add a and b it performs the addition, if c is in there, it stops the process and produces nothing.
My question is, how do we add the calculated number and append it to the beginning of the fixed value?
Also, the addition works, but not the way I want it to, I want to add the 3 numbers together, the javascript adds 456+12= 468
I know this is very simple code, I am not familiar with Javascript programming and I pretty much pieced together what I found from searching.
I hope this makes sense, if this is not possible I understand.
Thanks!
using parseInt on the values should help with the math. your results are currently inaccurate because the form values are strings: rather than adding numbers you are concatenating strings.
i changed your 'number' input to have an ID attribute, so that you can select with getElementById and replaced the eval call with a call to parseInt.
the value of c in the calculate function needs to be corrected though, not sure what you meant but that will generate an error.
other various HTML tidyness issues (nothing that would break, just easier to read IMHO).
<script type="text/javascript">
function calculate() {
var a = 12;
var b = parseInt(document.getElementById("number").value);
// var c = 5J7S;
var d = (a + b + c);
alert(d);
}
</script>
<form name="form">
Phone: <input type="text" size="3" value=""/>
-
<input type="text" name="number" id="number" size="3" value=""/>
-
<input type="text" size="4" value=""/>
<p>
<input type="button" name="b1" value="Grab Code" onclick="calculate()">
</p>
</form>
hope that helps! cheers.
I want to create a calculator which simply sums 2 fields up. But whatever I try it does not work. It also returns "NaN", also if I use parseInt().
Here's the code:
<script type="text/javascript" language="Javascript">
function doSum()
{
var a = document.getElementsByName("a").value;
var b = document.getElementsByName("b").value;
var sum = a + b;
document.getElementById("sum").value = sum;
}
</script>
<form action="" method="POST">
<br/>a:<br/>
<input type="text" name="a" onblur='doSum()' value="0" size="5" />
<br/>b:<br/>
<input type="text" name="b" onblur='doSum()' value="0" size="5" />
<br/>Ergebnis<br/>
<input type="text" id='sum' value='' size="50" disabled/>
</form>
Sorry for that noob question, but what I'am doing wrong?
Thanks for any help!
Give ids to your inputs and identify them uniquely using document.getElementById. Then, obtain their decimal int values using parseInt with the radix parameter set to 10 and display the result as you currently do.
<script type="text/javascript" language="Javascript">
function doSum()
{
var a = parseInt(document.getElementById("a").value, 10);
var b = parseInt(document.getElementById("b").value, 10);
var sum = a + b;
document.getElementById("sum").value = sum;
}
</script>
<form action="" method="POST">
<br/>a:<br/>
<input type="text" id="a" onblur='doSum()' value="0" size="5" />
<br/>b:<br/>
<input type="text" id="b" onblur='doSum()' value="0" size="5" />
<br/>Ergebnis<br/>
<input type="text" id='sum' value='' size="50" disabled/>
</form>
getElementsByName returns a list of elements and you'd have to refer to the one you want through an index, even if the list contains only one element.
getElementById on the other hand, returns an uniquely identified element, by its id.
use getElementById and give each of those an Id. getElementsByName returns an array. By the way.. it's not a bad question. It's a common error-- one that is addressed in a way by using jQuery which deals in wrapped sets.
getElementsByTagName returns a node list:
function doSum()
{
var a = document.getElementsByName("a")[0].value;
var b = document.getElementsByName("b")[0].value;
var sum = parseInt(a, 10) + parseInt(b, 10);
document.getElementById("sum").value = sum;
}
So you will need to index it. In addition in order not to do a string concate, parseInt with radix 10 is needed. Unless you plan to accept octal values in your calculator.
getElementsByName returns multiple elements, hence the plural Elements. You need to get the property of the first element found:
var a = document.getElementsByName('a')[0].value;
getElementsByName returns a NodeList: this is a set of all the elements found with that name. It is like an array in that you can use numeric indexes (like [0]) to access the elements found and in that there is a length property; no other array-like functionality is available.
Furthermore, the value property will always be a string if it is set. The + operator is the addition operator when the values are numbers; if they are strings, it is the concatenation operator. "1" + "2" is equal to "12" in Javascript. You need to use parseInt to convert them to numbers:
var a = document.getElementsByName('a')[0].value;
a = parseInt(a, 10); // parse as a number in base 10
Fields in JavaScript are all strings you need int, also .getElementsByName returns an array, you probably need the first element, so:
var a = parseInt(document.getElementsByName("a")[0].value, 10);
var b = parseInt(document.getElementsByName("b")[0].value, 10);
getElementsByName returns an array which gives you the wrong data type for what you are trying to do.
try:
function doSum()
{
var a = document.getElementById("a").value;
var b = document.getElementById("b").value;
var sum = a + b;
document.getElementById("sum").value = sum;
}
</script>
<form action="" method="POST">
<br/>a:<br/>
<input id="a" type="text" name="a" onblur='doSum()' value="0" size="5" />
<br/>b:<br/>
<input id="b" type="text" name="b" onblur='doSum()' value="0" size="5" />
<br/>Ergebnis<br/>
<input type="text" id='sum' value='' size="50" disabled/>
</form>
OK, two issues, your a fetching the valurs of a and b using getElementsByName which returns an array of values (since there could be many). Use getElementsById and put ids in the HTML.
Also the value properties will be strings so you will need to convert to numbers before doing your addition.
a and b are strings so :
function doSum()
{
var a = parseInt(document.getElementsByName("a").value);
var b = parseInt(document.getElementsByName("b").value);
var sum = a + b;
document.getElementById("sum").value = sum;
}