inputs need to equal zero before action - javascript

how can i get each input to equal zero before it is touched so that i dont get an error until every input is completed and not have it show in the input field. Also this is for money and im struggling to get the two decimal point thing down. thank you
<td>Subtotal</td>
<td class="total" id="tot" for="tot">
<input type="total" id="total">
<script type="text/javascript">
function myFunction()
{
var answer = document.getElementById('total');
var n = 0
var x = document.getElementById('itemprice');
var y = document.getElementById('itemprice1');
var z = document.getElementById('itemprice2');
//var d = document.getElementsById('itemprice3');
// parseFloat converts to values, otherwise you'll concatenate the strings.
answer.value = parseFloat(x[0].value) + parseFloat(y[0].value) + parseFloat(z[0].value); // + d.value;
}
</script>
</td>

give the item prices a zero default value:
<input type="total" id="itemprice" value="0.00">

Related

Unsure why my math min function is not working but math max function is in script code

function selectHighestNumber()
{
var valueFirstNumber;
var valueSecondNumber;
var valueThirdNumber;
var selectMaxNumber;
valueFirstNumber = document.getElementById("txtFirstNumberValue").value;
valueSecondNumber = document.getElementById("txtSecondNumberValue").value;
valueThirdNumber = document.getElementById("txtThirdNumberValue").value;
selectMaxNumber = Math.max(valueFirstNumber, valueSecondNumber, valueThirdNumber);
document.getElementById("selectRankingNumbersResults").innerHTML = selectMaxNumber;
}
function selectLowestNumber()
{
var valueFirstNumber;
var valueSecondNumber;
var valueThirdNumber;
var selectMinNumber;
valueFirstNumber = document.getElementById("txtFirstNumberValue").value;
valueSecondNumber = document.getElementById("txtSecondNumberValue").value;
valueThirdNumber = document.getElementById("txtThirdNumberValue").value;
selectMinNumber = Math.min(+valueFirstNumber, +valueSecondNumber, +valueThirdNumber);
document.getElementById("selectRankingNumbersResults").innerHTML = selectMinNumber;
}
<main class="fancy-border">
<form id="userNumberEntry">
<p><label for="txtFirstNumberValue">Enter your first number here:</label>
<input type="text" id="txtFirstNumberValue" maxlength="20" size="20"></p>
<p><label for="txtSecondNumberValue">Enter your second number here:</label>
<input type="text" id="txtSecondNumberValue" maxlength="20" size="20"></p>
<p><label for="txtThirdNumberValue">Enter your third number here:</label>
<input type="text" id="txtThirdNumberValue" maxlength="20" size="20"></p>
<p><input type="button"
value="Find the highest number"
id="btnSubmit"
onclick="selectHighestNumber();">
</p>
<p><input type="button"
value="Find the lowest number"
id="btnSubmit"
onlick="selectLowestNumber();">
</p>
<br>
<div id="selectRankingNumbersResults">
</div> <!--end of selectRankingNumberValues div-->
</form>
</main>
So very recently I came into a problem in my script where I was unsure why my Math min function was not working. I asked about that issue in a previous question and found that a spelling error was causing one of my functions to not work. Essentially, I have two functions, a math min, and a math max, both serving similar purposes. I am working in Html code, and use a script for my functions within my Html document. The purpose of this math min and math max function is that I have three text boxes to input numbers into, there are two buttons that will either serve to show the highest or lowest of these three values. My math max function works fine and shows the highest value, however, my math min function does not. It does not return any value at all. I have cross-checked my code to see if it was misspelled, spacing errors, or other mismatched words with the rest of my code but none of it seems to be the problem. This is how my math max and math min functions in my script look respectively.
function selectHighestNumber()
{
var valueFirstNumber;
var valueSecondNumber;
var valueThirdNumber;
var selectMaxNumber;
valueFirstNumber = document.getElementById("txtFirstNumberValue")
.value;
valueSecondNumber = document.getElementById("txtSecondNumberValue")
.value;
valueThirdNumber = document.getElementById("txtThirdNumberValue")
.value;
selectMaxNumber = Math.max(valueFirstNumber, valueSecondNumber,
valueThirdNumber);
document.getElementById("selectRankingNumbersResults").innerHTML =
selectMaxNumber;
}
function selectLowestNumber()
{
var valueFirstNumber;
var valueSecondNumber;
var valueThirdNumber;
var selectMinNumber;
valueFirstNumber = document.getElementById("txtFirstNumberValue")
.value;
valueSecondNumber = document.getElementById("txtSecondNumberValue")
.value;
valueThirdNumber = document.getElementById("txtThirdNumberValue")
.value;
selectMinNumber = Math.min(valueFirstNumber, valueSecondNumber,
valueThirdNumber);
document.getElementById("selectRankingNumbersResults").innerHTML =
selectMinNumber;
}
If anyone could help me understand where I might be going wrong, that would be greatly appreciated! I am very confused about what I could have coded wrong, so any insight/outlook is greatly appreciated!
Math.max and Math.min will return the largest/smallest value (or -Infinity/Infinity if no values are supplied) and then convert to a number if they're not already, this means that strings will first be compared as strings and not numbers ("123" > "3"), so you should first convert each value to a number.
Also I recommend batching up the whole process instead of getting each element separately, reading its value, converting it to a number, checking it's valid, passing it to the function. So try to do the whole thing in a loop of some sort.
document.querySelector("form").addEventListener("submit", function(event) {
event.preventDefault();
console.log("Max:" + getEdgeCase(true));
console.log("Min:" + getEdgeCase(false));
});
function getEdgeCase(flag) {
// get all the inputs in one go and convert them to an array
var inputList = [].slice.call(document.querySelectorAll("form input[type=\"number\"]"));
var inputList = inputList.map(function(input) {
// convert to number, if it's not a valid number and ends up as NaN then return 0
return +input.value || 0;
});
// get the right function and call apply (spreads an array into arguments)
return Math[flag ? "max" : "min"].apply(Math, inputList);
}
<form>
<input type="number" />
<input type="number" />
<input type="number" />
<input type="submit" />
</form>

javascript on input field addition

//// JavaScript function to add input values display into another input field
function calculate() {
var x = document.getElementById('fee_selector_holder').value;
var y = document.getElementById('content').value;
var result = document.getElementById('result');
var myResult = x + y;
result.value = myResult;
}
<input type="text" name="hostelfees" id="content" oninput="calculate()">
<input type="text" name="fee_id" id="fee_selector_holder" oninput="calculate()">
<input type="text" id="result" name="totalfee">
I am giving values to input fields its adding concatination but not adding please verify it on input function is correct or wrong once verify then reply me thats it my question.
You have strings, that is why it is concatenating. Make integers with:
http://www.w3schools.com/jsref/jsref_parseint.asp
And it will work well.
First, when you read values from DOM, they are read as string. You will have to use parseInt or parseFloat to convert string to integer.
Second, + operator has a override function for string to act as concatenation operator.
Also notice, I have used .value || 0. Here if value does not exist, performing arithmetic operation over it will return NaN so adding default value (0).
//// JavaScript function to add input values display into another input field
function calculate() {
var x = document.getElementById('fee_selector_holder').value || 0;
var y = document.getElementById('content').value || 0;
var result = document.getElementById('result');
var myResult = parseInt(x) + parseInt(y);
result.value = myResult;
}
<input type="text" name="hostelfees" id="content" oninput="calculate()">
<input type="text" name="fee_id" id="fee_selector_holder" oninput="calculate()">
<input type="text" id="result" name="totalfee">
You have to parse the input values to integer as all input values are string by default:
//// JavaScript function to add input values display into another input field
function calculate() {
var x = document.getElementById('fee_selector_holder').value || 0; // default value 0 if input is blank
var y = document.getElementById('content').value || 0; // default value 0 if input is blank
var result = document.getElementById('result');
var myResult = parseInt(x, 10) + parseInt(y, 10); // parse it here
result.value = myResult;
}
<input type="text" name="hostelfees" id="content" oninput="calculate()">
<input type="text" name="fee_id" id="fee_selector_holder" oninput="calculate()">
<input type="text" id="result" name="totalfee">
You should add attribute to result
result.setAttribute("value", myResult);

getting wrong output on the second function

I have a code in which I have two functions:
In first function hardcode value is going
In second function value is going dynamically.
Here is my HTML
<input type="text" name="txt1" id="txt1">
<input type="text" name="txt2" id="txt2">
<input type="text" name="txt3" id="txt3">
<input type="submit" value= "ADD Value" onclick="Addhardcode(1,2,3)">
<input type="submit" value="Add" onclick ="Add()">
Script:
<script type="text/javascript">
<!--
function Addhardcode(a,b,c)
{
a+b+c;
alert(a+b+c);
}
function Add()
{
var x= document.getElementById("txt1")
var y= document.getElementById("txt2")
var z= document.getElementById("txt3")
var a=x.value;
var b=y.value;
var c=z.value;
Addhardcode(a,b,c);
}
//-->
</script>
While Clicking on button ADD Value I get right answer but, on clicking on button Add I am not getting right answer. If I pass 4 ,5& 6 in the textbox then the output come as 456 in place of 15. What am I doing wrong. If i have to make an validation on the text boxes that it take only numbers or it cannot be empty . then what can i do for that
The reason you are getting the concatenated answer is because JavaScript will see the passed arguments as strings. They are being passed as strings because they are pulled from the textbox's value property, which is a string.
This would be the equivalent of doing this:
alert('4'+'5'+'6'); // Gives '456'
To actually add the numbers, you need to convert them to integers first.
var a = parseInt(x.value);
var b = parseInt(y.value);
var c = parseInt(z.value);
When you currently call x.value it returns as a string, so the + operator will just be concatenating the values.
Use parseInt() to parse the values into integers.
var a = parseInt(x.value);
var b = parseInt(y.value);
var c = parseInt(z.value);
in your code a,b,c are considered as strings and so + is just appending them.
you have to convert them into integer like
var a= parseInt(x.value,10);
var b= parseInt(y.value,10);
var c= parseInt(z.value,10);
before passing on to function Addhardcode

from a html form to javascript

I have a form that requires three inputs as follows:
<form>
<input name="mn"
type="number"
min="1"
value="1">
<input name="mx"
type="number"
min="2"
value="10">
<input name="step"
type="number"
min="1"
value="1">
<input onclick="myfunc()"
type="submit"
value="calculate">
</form>
all i require is to be able to access the three fields directly in javascript. I do not need to pass the information anywhere else.
Could anyone point me in the right direction? I have read examples where there has been one input, but not multiple.
<script type="text/javascript">
function myfunc() {
var mn = document.getElementsByName("mn")
var mx = document.getElementsByName("mx")
var step = document.getElementsByName("step")
alert((mn + mx) / step)
}
</script>
Give your form an id like so
<form id="myForm">
The other thing to watch out for is that the is that the value attribute is a string so adding the two values concatenates them rather than summing them.
Try instead
var frm = document.forms["myForm"];
var _mn = parseInt( frm["mn"].value );
var _mx = parseInt( frm["mx"].value );
var _step = parseInt( frm["step"].value );
var result = ( _mn + _mx ) / _step;
I'd start with giving each input an id then i could use:
var min = document.getElementById('mn')
and so on. To access the value you simply would call
min.value
Also there is no point in removing the i from min and the a from max. That is not optimized just hard to read and understand.
Try this:
<script type="text/javascript">
function myfunc() {
var mn = document.getElementsByName("mn")[0].value;
var mx = document.getElementsByName("mx")[0].value;
var step = document.getElementsByName("step")[0].value;
var top = mn / mx;
alert(top / step);
}
</script>
if u need to access to the values of the inputs change your code to:
function myfunc() {
var mn = document.getElementsByName("mn")[0];
var mx = document.getElementsByName("mx")[0];
var step = document.getElementsByName("step")[0];
// you may need to validate your values here, like step.value != 0
alert((mn.value + mx.value) / step.value)
}

Calculating loan payment in Javascript

I am making a loan payment calculator on my website (www.kreditrunner.dk - In the bottom of the page).
EDIT: Problem solved with the following equation:
var princ = document.getElementById("amount").value;
var intr = document.getElementById("earlypercent").value/1200;
var term = document.getElementById("time").value;
document.getElementById("result").value = princ * intr / (1 - (Math.pow(1/(1 + intr), term)));
And also i used a keyup function instead. Cause when the key is pressed down, the input hasn't received the value yet, hence the wrong result :)
ORIGINAL POST:
I have my four inputs with respectively amount, interest rate per year in percent, payment period, and result.
<table>
<tr>
<td width="150">
<label for="amount">Lånebeløb (DKK)</label>
<input type="text" id="amount" name="amount" class="input-small">
<label for="earlypercent">ÅOP (%)</label>
<input type="text" id="earlypercent" name="earlypercent" class="input-small">
</td>
<td>
<label for="time">Løbetid (Mdr)</label>
<input type="text" id="time" name="time" class="input-small">
<label for="result"><b>Månedlig betaling (DKK)</b></label>
<input type="text" id="result" name="result" class="input-medium">
</td>
</tr>
</table>
For each of the first three input I have the listed calculations seen below which is derived from the following equation: http://www.wikihow.com/Calculate-a-Loan-Payment
$('#amount').keydown(function () {
var amount = document.getElementById("amount").value;
var earlypercent = document.getElementById("earlypercent").value;
var monthlypercent = earlypercent / 12 * 100;
var time = document.getElementById("time").value;
var negativetime = time * (-1);
var result = 1 + monthlypercent;
result = Math.pow(result, negativetime);
result = 1 - result;
result = monthlypercent / result;
document.getElementById("result").value = result * amount;
});
However, my result is weird as ****. As you can see when you try (e.g. with values, 1000, 10%, 12 months) the result is 8333.33 where it should have been around 83.33. Well actually it should be around 87.95.
So i could move the *100 in the montlypercent, however as you see when write an amount and tab to the next input field, the result changes even though the values are the same. Cant seem to get the equation right and the keydown function bothers me :/
Please help :)

Categories

Resources