[enter image description here][1]
[1]: https://i.stack.imgur.com/ztI16.png the variable ns in the image is making problem and not giving the result needed plz suggest the proper way of writting it .
The code image you posted has some problems:
y is not checked for being a number (the input allows strings!)
I don't see code processing the input (like the input with ID a)
So, it seems that your code logic works, but some small things need fixing.
const salaryInput = document.getElementById("a")
salaryInput.addEventListener('input', function(e) {
var x, y;
x = document.getElementById("n").value;
// checking whether y is a number - if not, treat it as 0
y = isNaN(document.getElementById("a").value) ? 0 : Number(document.getElementById("a").value);
var TA = 0.20 * y;
var DA = 0.15 * y;
var HRA = 0.50 * y;
var PF = 0.20 * y;
var NS = y + TA + DA + HRA + PF
// rounding values with toFixed()
document.getElementById("T").value = TA.toFixed(2)
document.getElementById("D").value = DA.toFixed(2)
document.getElementById("H").value = HRA.toFixed(2)
document.getElementById("P").value = PF.toFixed(2)
document.getElementById("NE").value = NS.toFixed(2)
})
<label for="n">NAME: <input id="n" type="text"></label><br />
<label for="a">BASIC SALARY: <input id="a" type="text"></label><br /><br />
<label for="T">TA: <input id="T" type="text" readonly></label><br />
<label for="D">DA: <input id="D" type="text" readonly></label><br />
<label for="H">HRA: <input id="H" type="text" readonly></label><br />
<label for="P">PF: <input id="P" type="text" readonly></label><br />
<label for="NE">NS: <input id="NE" type="text" readonly></label>
Please note that the snippet above is on no way a "good code" - I just formatted it to use elements you might find similar to your code. Please note that I used <label> instead of <span> to wrap input fields.
Related
I'm new to JavaScript and I'm having trouble trying to make my functions work properly.
function myFunction() {
// This part appends a number before a label with the class "enum"
var enumField = document.getElementsByClassName('enum');
for (var z = 0; z <= enumField.length; z++) {
var span = document.createElement('span');
span.innerHTML = z + 1 + '.- ';
enumField[z].parentNode.insertBefore(span, enumField[z]);
}
//This other part changes the background color of an element with the class "fieldsetColor"
var fieldsetStyle = document.getElementsByClassName('fieldsetColor');
for (var i = 0; i <= fieldsetStyle.length; i++) {
fieldsetStyle[i].style.backgroundColor = 'palegoldenrod';
}
}
<body onload="myFunction();">
<div>Student</div>
<form id="myForm">
<fieldset class="fieldsetColor">
<legend>Personal Data </legend>
<img src="http://via.placeholder.com/100x100?text=Placeholder"><br>
<label class="reqInput enum" for="nombreInput">Nombre: </label>
<input id="nombreInput" name="nombre" type="text">
<label class="reqInput enum" for="nombreInput">Nombre: </label>
<input id="nombreInput" name="nombre" type="text">
<label class="reqInput enum" for="nombreInput">Nombre: </label>
<input id="nombreInput" name="nombre" type="text">
</fieldset>
</form>
</body>
The main problem is that only the first part of the function works (the one that enumerates), and the second part does not work.
If I swap the position of the first part and the second one, the same happens (only the background color is changed).
What could be the problem? Is my syntax wrong? Is something wrong with the <body onload="myFunction()">?
I'm really afraid that this could be silly question... I'm trying to learn by myself but sometimes I get lost and can't seem to formulate the right question...
Thanks in advance! ☺
It's caused by your for loop condition. You probably get an Array Index Out of Bounds exception.
you use
z <= enumField.length
but it should be
z < enumField.length
You're actually just looping once more than you need to. Since arrays are zero indexed, you don't want z <= enumField.length but rather z < enumField.length. Since this error was halting the function, nothing continued.
function myFunction() {
// This part appends a number before a label with the class "enum"
var enumField = document.getElementsByClassName('enum');
for (var z = 0; z < enumField.length; z++) {
var span = document.createElement('span');
span.innerHTML = z + 1 + '.- ';
console.log(enumField[z]);
enumField[z].parentNode.insertBefore(span, enumField[z]);
}
//This other part changes the background color of an element with the class "fieldsetColor"
var fieldsetStyle = document.getElementsByClassName('fieldsetColor');
for (var i = 0; i <= fieldsetStyle.length; i++) {
fieldsetStyle[i].style.backgroundColor = 'palegoldenrod';
}
}
<body onload="myFunction();">
<div>Student</div>
<form id="myForm">
<fieldset class="fieldsetColor">
<legend>Personal Data </legend>
<img src="http://via.placeholder.com/100x100?text=Placeholder"><br>
<label class="reqInput enum" for="nombreInput">Nombre: </label>
<input id="nombreInput" name="nombre" type="text">
<label class="reqInput enum" for="nombreInput">Nombre: </label>
<input id="nombreInput" name="nombre" type="text">
<label class="reqInput enum" for="nombreInput">Nombre: </label>
<input id="nombreInput" name="nombre" type="text">
</fieldset>
</form>
I'm just trying to input an number and then add 10% and then take that total and .08% tax. Can you please help me figure out what I'm doing wrong. I sure it is something simple I'm overlooking but I'm new to this and can't figure what is wrong.
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Price tool</title>
</head>
<body>
<form name="operation_form">
<label style="font-size:20px"><b>Price Tool</b></label>
<br/>
<br/>
<br/>
<label>Item Price: </label><input type="number" name='acertscore' value="" />
<br/>
<br/>
<label><b>Total is:</b></label><input type="number" name="answerbox">
<br/>
<input type="button" value="Calculate" onclick="costCalc();" />
<br/>
<input type="button" value="Reset" onClick="this.form.reset()" />
</form>
<script type="text/javascript">
function costCalc() {
var form = document.forms["operation_form"];
var x = form["acertscore"].value;
var cost = (x * .1) + x;
var answer = (cost * .08) + cost;
form["answerbox"].value = answer;
}
</script>
</body>
</html>
I logged the value of 'cost' in your code when I start with the value 100
var cost = (x * .1) + x;
console.log(cost);
and got a value of '10100'
But if I make sure that x is a number I get the correct value (110)
var cost = (x * .1) + Number(x);
console.log(cost);
And I get 118.8 for the total.
When you retrieve the value from your input control, it comes through as a string value.
var x = form["acertscore"].value; // x is a string
If you convert this to a number immediately you'll avoid additional problems.
var x = Number(form["acertscore"].value); // x is a number
function costCalc() {
var form = document.forms["operation_form"];
var x = Number(form["acertscore"].value);
var cost = (x * .1) + x;
var answer = (cost * .08) + cost;
form["answerbox"].value = answer;
}
<form name="operation_form">
<label style="font-size:20px"><b>Price Tool</b></label>
<br/>
<br/>
<br/>
<label>Item Price: </label><input type="number" name="acertscore" value="" />
<br/>
<br/>
<label><b>Total is:</b></label><input type="number" name="answerbox">
<br/>
<input type="button" value="Calculate" onclick="costCalc();" />
<br/>
<input type="button" value="Reset" onClick="this.form.reset()" />
</form>
The problem is that your answer number is so long that it tries to display exponents. Because of this, the number gets treated as a string, though you've specified that the output goes into an <input> field with a type of number. Because your answer is not a number, it can't be displayed.
To resolve this, you can parse the output as a float before displaying it:
form["answerbox"].value = parseFloat(answer);
function costCalc() {
var form = document.forms["operation_form"];
var x = form["acertscore"].value;
var cost = (x * .1) + x;
var answer = (cost * .08) + cost;
form["answerbox"].value = parseFloat(answer);
}
<form name="operation_form">
<label style="font-size:20px"><b>Price Tool</b></label>
<br/>
<br/>
<br/>
<label>Item Price: </label><input type="number" name='acertscore' value="" />
<br/>
<br/>
<label><b>Total is:</b></label><input type="number" name="answerbox">
<br/>
<input type="button" value="Calculate" onclick="costCalc();" />
<br/>
<input type="button" value="Reset" onClick="this.form.reset()" />
</form>
Hope this helps!
The code below is working fine but what if there are 100 inputs? any shorter way to do this?
function checkTotal() {
var a = document.getElementById("sandwich").value;
var b = document.getElementById("burger").value;
var c = document.getElementById("cake").value;
var d = document.getElementById("coffee").value;
document.getElementById("total").value = parseInt(a) * 10 + parseInt(b) * 5 + parseInt(c) * 15 + parseInt(d) * 20;
}
<form role="form" name="listForm">
<label>Sandwich</label>
<input type="number" id="sandwich" value="0" onkeyup="checkTotal()"><br>
<label>Burger</label>
<input type="number" id="burger" value="0" onkeyup="checkTotal()"><br>
<label>Cake</label>
<input type="number" id="cake" value="0" onkeyup="checkTotal()"><br>
<label>Coffee</label>
<input type="number" id="coffee" value="0" onkeyup="checkTotal()"><br> Total: <input type="text" size="2" name="total" id="total" value="0" />
</form>
1) Here each input article has a different price.
2) The value of the input should be mutiply with its price given(Eg. if the sandwich has a price:30, and user inputs value 2 it should calculte the total=price*input value.)
3) i have my code which is working fine but is the above code is the right way to do?
4) what if there are 100 of article inputs. is there shorter code or should i create variable for each one?
what if there are 100 of article inputs. is there shorter code or
should i create variable for each one?
You can maintain a map
var idPriceMap = {
"sandwich" : 20,
"burger" : 10,
"cake" : 5,
"coffee" : 10
};
You can iterate this and produce your value using reduce
var output = Object.keys( idPriceMap ).reduce( function(a,b){
var value = +document.getElementById( b ).value;
a += value * idPriceMap[ b ];
return a;
}, 0);
document.getElementById( "total" ).value = output;
Another way to try is to give your elements a class and some data attributes that can be retrieved by JavaScript using dataset. You can then use them to make your calculations. That way you get rid of ids and you just have to change the HTML code to add a new element.
function checkTotal() {
var total = 0,
foods = document.querySelectorAll('.food');
for (var i = 0; i < foods.length; i++) {
var food = foods[i],
name = food.dataset.item,
price = parseInt(food.dataset.price),
howMany = parseInt(food.value);
console.log(howMany, name, 'costs', (howMany * price));
total += howMany * price;
}
document.getElementById('total').value = total;
}
<form role="form" name="listForm">
<label>Sandwich</label>
<input class="food" data-item="sandwich" data-price="30" type="number" value="0" onBlur="checkTotal()"><br>
<label>Burger</label>
<input class="food" data-item="burger" data-price="10" type="number" value="0" onBlur="checkTotal()"><br>
<label>Cake</label>
<input class="food" data-item="cake" data-price="5" type="number" value="0" onBlur="checkTotal()"><br>
<label>Coffee</label>
<input class="food" data-item="coffee" data-price="15" type="number" value="0" onBlur="checkTotal()"><br>
Total: <input type="text" size="2" name="total" id="total" value="0" />
</form>
As a side note, you should give a try on Angular or Knockout which can help you to achieve those operations.
I am trying to get the values from my form into a function and return a value
Here is my function
function createInput(){
var weight;
weight = document.bmiCalc.weight.value;
var height = getElementById('height').value;
input.onclick = function calcBMI()
{
// calculate users BMI
var BMI = weight * 703 / Math.pow(height, 2);
return BMI;
}
document.getElementById("BMI").appendChild();
}
and here is my form code from my html page
<form id="bmiCalc">
<h2> Calculate your Current BMI</h2>
<p><label> Please enter your weight in lbs: <input type="text" name = "weight" id= "weight"></label></p>
<p><label> Please enter your height in inches: <input type="text" name ="height" id="height"></label>
<button type="submit">Submit</button></p>
<p><label> Your current BMI is: <input name="BMI" id="BMI"></label></p>
</form>
Changed your html and js:
http://jsfiddle.net/CQxnx/
html:
<h2> Calculate your Current BMI</h2>
<label> Please enter your weight in lbs:</label> <input type="text" name="weight" id="weight">
<br />
<label> Please enter your height in inches:</label> <input type="text" name="height" id="height">
<br />
<input type="button" value="calculate" onclick="calcBMI();" />
<br />
<div id="msg"></div>
js:
function calcBMI(){
var weight = document.getElementById('weight').value;
var height = document.getElementById('height').value;
// calculate users BMI
var BMI = weight * 703 / Math.pow(height, 2);
var msg = document.getElementById('msg');
msg.innerHTML = 'Your current BMI is:' + BMI;
}
You seem to be a bit off, but you never actually call the createInput function. Even after that, you don't actually append the input button. There is no BMI ID element, and createInput would calculate the weight/height as they are when it's called, not when the button is clicked.
Instead, you should just put the button in the DOM to begin with and bind the calculation function to it.
document.getElementById('calculate').addEventListener('click', function () {
document.getElementById("BMI").textContent =
document.getElementById('weight').value * 703 /
Math.pow(document.getElementById('height').value, 2);
});
http://jsfiddle.net/fsKNb/
I have some line of javascript which is works well if it gets value from the same series of names. But I have a problem later when each values passed to another page which I'd like to break down which value is belongs to. So the question is how can I change the way the script calculate the value from 'name' to 'id'. As the codes below:
<script type="text/javascript">
//auto commas
function doThousands(n) {
n = '' + n;
if (n.length < 4) return n;
var c = n.length % 3;
var pre = n.substring(0, c);
return pre + (pre.length? ',' : '') + n.substring(c).match(/\d{3}/g).join(',');
}
//sub total
function checkTotal() {
document.cc_form.total.value = '';
var sum = <?=$days*$_rate*$_rooms?>;
for (i=0;i<document.cc_form.cost.length;i++) {
if (document.cc_form.cost[i].checked) {
sum = sum + parseInt(document.cc_form.cost[i].value);
}
}document.cc_form.total.value = doThousands(sum);
}
</script>
And this is the HTML:
<form name="cc_form" id="cc_form" method="post" action="/">
<label for="transfer1"><input type="checkbox" id="transfer1" name="cost" value="800" autocomplete="off" onchange="checkTotal()" /> Taxi (800 THB | 2 pax)</label><br />
<label for="transfer2"><input type="checkbox" id="transfer2" name="cost" value="1200" autocomplete="off" onchange="checkTotal()" /> Mini Van (1,200 THB | 6 pax)</label><br />
<label for="xbed"><input type="checkbox" id="xbed" name="cost" value="1200" autocomplete="off" onchange="checkTotal()" /> Extra Bed (1,200 THB)</label><br />
<input type="text" id="total" name="total" />
</form>
document.getElementById http://www.w3schools.com/jsref/met_doc_getelementbyid.asp