Javascript button not working with function - javascript

I can't figure out why this function is not working. Assignment instructions call for the javascript function code to be in it's own javascript file.
Here is the html
<h2>BMI Calculator</h2>
<form>
<input type="text" id="weight" value="0" />
<label for="weight">Weight in pounds</label>
<input type="text" id="height" value="0" />
<label for="height">Height in inches</label>
<input type="text" id="Result" value="0" />
<label for="Result"> BMI Result </label>
<input type="submit" id="submit" value="Calculate BMI" />
</form>
Here is the function based on that form. It's supposed to calculate the bmi.
function calcBMI() {
var weight = parseInt(document.getElementByID("weight").value);
var height = parseInt(document.getElementByID("height").value);
var result = (weight * 703) / (height * height);
var textbox = document.getElementById('Result').value;
textbox.value = result;
}
document.getElementById("submit").addEventListener("click", calcBMI, false);

3 things:
getElementById must be in camel case. Not with capital D's at the end
Reference to textbox should be just var textbox = document.getElementById('Result') and not with .value at the end.
Button's type should be button otherwise the form is being posted.
Your working example:
function calcBMI() {
var weight = parseInt(document.getElementById("weight").value);
var height = parseInt(document.getElementById("height").value);
var result = (weight * 703) / (height * height);
var textbox = document.getElementById('Result');
textbox.value = result;
}
document.getElementById("submit").addEventListener("click", calcBMI, false);
<h2>BMI Calculator</h2>
<form>
<input type="text" id="weight" value="0" />
<label for="weight">Weight in pounds</label>
<input type="text" id="height" value="0" />
<label for="height">Height in inches</label>
<input type="text" id="Result" value="0" />
<label for="Result"> BMI Result </label>
<input type="button" id="submit" value="Calculate BMI" />
</form>

1.
At a glance it seems as though you are not preventing the default browser behaviour, you need to use event.preventDefault() to prevent the form submitting.
function [...](e) {
e.preventDefault();
[...]
}
2.
Ensure you DOM has loaded before manipulation begins by loading the JavaScript below the HTML or you can make use of the DOMContentLoaded event.
3.
A sanity check, ensure that the script has been loaded using the <script></script> tags. If it is an external file, use the src property, if it is just code, wrap it in the aforementioned tags.
4.
You need to change the usage of getElementById you have used getElementByID instead of the lowercase d in Id.
5.
When you are doing textbox.value = result; what you are actually doing is textbox.value.value = result; as you have referenced it as .value originally.
Finally,
Make use of the console as it'll have saved you from asking here as the errors are thrown in them.

There are few problems with your function:
You have a typo in document.getElementByID, it should be document.getElementById
You have to pass an event object into your function, and invoke preventDefault, so that your form won't be submitted to the server
the line:
var textbox = document.getElementById('Result').value;
it should be
var textbox = document.getElementById('Result');
So overall, your function should look like:
function calcBMI(e) {
e.preventDefault();
var weight = parseInt(document.getElementById("weight").value);
var height = parseInt(document.getElementById("height").value);
var result = (weight * 703) / (height * height);
var textbox = document.getElementById('Result');
textbox.value = result;
}

Use on click event, change your getElementByID to getElementById and change the type to button and not submit. Submit would post it but what you need is to call the function.
<input type="button" id="submit" value="Calculate BMI" onclick="calcBMI()"/>
In your javascript change
var textbox = document.getElementById('Result').value
To
var textbox = document.getElementById('Result').value = result;
And remove
textbox.value = result;

You made a mistake here in weight and heightIt should be in camel case only.
document.getElementById("your id")
and also why not you check in console what error it shows

Related

How to print the values in the same input text field using JS

I have created 5 input text boxes using HTML and made a button while clicking the button the values will print the result input text box. The first 4 fields are my inputs and the last text field is my output. unable to debug the issue. kindly find the code and help to find the issue.
function JS(){
var h=document.getElementById('h').value;
var w=document.getElementById('w').value;
var g=document.getElementById('g').value;
var t=document.getElementById('t').value;
var total =(h+w+g+t);
document.getElementById('result').innerHTML=total;
}
<h2> Calculator</h2>
<input type="text" placeholder="value1" id="h">
<input type="text" placeholder="value2"id="w">
<input type="text" placeholder="value3" id="g">
<input type="text" placeholder="value4" id="t">
<input type="text" placeholder="result" id="result">
<!--
<p
id="result">
</p>
-->
<button id="btn" onClick="JS()">Calculate</button>
There are two keys to resolving your issue:
Coerce your inputs to numbers, which I'm doing by adding a + in front of the value assignments. If you don't do this, your values may be treated like strings and concatenated rather than added like numbers.
Set the value of the input element, not the innerHTML. If you'd rather use a <p> element, which it appears you commented out in your sample code (and which I restored for completeness of my answer), consider using innerText.
See example here:
function JS() {
var h = +document.getElementById('h').value;
var w = +document.getElementById('w').value;
var g = +document.getElementById('g').value;
var t = +document.getElementById('t').value;
let p_result = document.getElementById('p_result');
var total = (h + w + g + t);
document.getElementById('result').value = total;
p_result.innerText = total;
}
<h2> Calculator</h2>
<input type="text" placeholder="value1" id="h">
<input type="text" placeholder="value2" id="w">
<input type="text" placeholder="value3" id="g">
<input type="text" placeholder="value4" id="t">
<input type="text" placeholder="result" id="result">
<br>
<p id="p_result" style="color:red;"></p>
<br>
<button id="btn" onClick="JS()">Calculate</button>
function JS(){
var h=document.getElementById('h').value;
var w=document.getElementById('w').value;
var g=document.getElementById('g').value;
var t=document.getElementById('t').value;
var total =(Number(h)+Number(w)+Number(g)+Number(t));
document.getElementById('result').value =total;
}
.value instead of .innerHTML
also, you should convert inputs values to number cause instead of making the sum will be as consider them string( for example if you type 1 , 2 , 3 , 4 without converting to number will be 1234 if you convert to number will be 10

Why is a HTML form field showing the calculations in the output field

I've created a basic profit calculator which is pretty much working fine. My issue is that every time I enter a number into each of the relevant fields, you can see the workings out in the "Total profit" field. It first tells me my entry is NaN, then -infinity, and then shows the workings. Once I click on my calculate button, I am then finally displayed with the correct number.
For this post I am not concerned with why it is producing the NaN (not a number), but why am I seeing it populated in the field in the first place. I want this field to remain blank until I click Calculate, and then see the resulting number. I suspect it's to do with my JavaScript code but I am a complete newbie - and very stuck.
Your thoughts are most appreciative.
<form id="profitCalculator" action="" class="dark-matter">
<h1>Profit Calculator</h1>
<fieldset>
<p><label>Case Cost:<br />£
<input name="casecost" type="text" value="" size="14" maxlength="8" /></label></p>
<p><label>Units per case:<br /> <input name="packs" type="text" value="1" size="14" maxlength="8" /></label></p>
<p><label>Sell price:<br /> £ <input name="sell_price" type="text" value="" size="14" maxlength="8" /></label></p>
<p><input type="button" class="button" OnClick="Circle_calc(this.form);" value="Calculate"></p>
<p>Total Profit:<br /> £ <input name="profit" type="text" value="0" autocomplete="off" SIZE=14></p>
<p><input type="reset" class="button" value="Reset"></p>
</fieldset>
</form>
And the JavaScript
<script type="text/javascript">
document.getElementById('profitCalculator').onclick = function () {
var casecost = this.elements['casecost'].value || 0;
var packs = this.elements['packs'].value || 0;
var sell_price = this.elements['sell_price'].value || 0;
var profit = (sell_price - casecost) / packs;
this.elements['profit'].value = profit.toFixed(2);
}
</script>
Thank you
You've set a click handler on the form element. Since click events bubble, clicks on the elements inside the form bubble to the form as well. So that's triggering an update to your profit element on anything that any element considers a click.
This diagram from the DOM3 events spec (which has since been folded into the DOM4 spec's events section) may help clarify how bubbling works:
You have a Onclick event on your button that calls Circle_calc function.
Change your function passing the form element as a parameter, and it will work.
Circle_calc = function (form) {
var casecost = form.elements['casecost'].value || 0;
var packs = form.elements['packs'].value || 0;
var sell_price = form.elements['sell_price'].value || 0;
var profit = (sell_price - casecost) / packs;
form.elements['profit'].value = profit.toFixed(2);
}
JsFiddle here

javascript not reading entered value in input box

I am unable to get the function AreaT() to verify and validate the entered value in the input box as the answer to the area of a triangle.
I keep getting "wrong" message even for the correct answer.
What am I doing wrong?
Thank you for taking the time to check my code.
<html>
<head>
<script>
var height = Math.floor(Math.random()*20 +1);
var base = Math.floor(Math.random()*30 +2);
var area = getElementById("area");
function AreaT(){
document.getElementById('height').value = height;
document.getElementById('base').value = base;
if(area== 1/2 * base * height){
document.write("correct")
}
else{
document.write("wrong");
}
}
</script>
</head>
<body>
<form>
<h2>HEIGHT:</h2><input type="button" size="20" id="height"/>
<h2>BASE: </h2><input type="button" size="20" id="base"/>
<h2>AREA: </h2>Enter The Area here:<input type="text" size="20" id="area"/>
<input type="button" size="20" value = "Calculate" onClick ="AreaT()"/>
</form>
</body>
</html>
Try this:
HTML
<body>
<h2>HEIGHT:</h2><input type="button" size="20" id="height"/>
<h2>BASE: </h2><input type="button" size="20" id="base"/>
<h2>AREA: </h2>Enter The Area here:<input type="number" size="20" id="area"/>
<input type="button" size="20" value = "Calculate" onClick ="AreaT()"/>
</body>
Javascript (put in <header> tag)
var height = Math.floor(Math.random()*20 +1);
var base = Math.floor(Math.random()*30 +2);
document.getElementById('height').value = height;
document.getElementById('base').value = base;
function AreaT(){
var area = document.getElementById("area").value;
if(area == 1/2 * base * height){
document.write("correct")
}
else{
document.write("wrong");
}
}
Adding on to what was already mentioned, you need to add a .value to the area element as well. I also changed the input type of AREA to number.
Change getElementById("area") to document.getElementById("area").value. You also need to assign area from inside your AreaT() function, otherwise it's not gonna get the value that the user typed in.
Also, your javascript needs to be below those form elements, otherwise it can't "see" them and you will get undefined values.

calculate division of fields dynamically using Jquery or Javascript

I'm "trying" to figure out how to calculate a division between to fields dynamically to display in another field, the thing is, all examples I've seen are sums, and those used something like this: $('#field').each(function(){....});.
I can't do that because there's no way of know which is the dividend and which is the divisor. I tried using "bind", to try to attach the function to the field. It didn't work.
Also tried putting "onChange="CalcularSaldo()" on the input field; no luck, but mainly because i'm pretty sure my function is wrong:
<script type="text/javascript">
$(document).ready(function() {
function calcularSaldo() {
var costo = document.getElementById("costo_ad").value;
var vida = document.getElementById("vida_util").value;
document.getElementById("saldo_dep").value = costo / vida;
}
});</script>
Inputs:
<label for="costo_ad">Costo de Adquisicion</label>
<input name="costo_ad" type="text" id="costo_ad" class="round default-width-input" />
<label for="vida_util">Vida Util</label>
<input name="vida_util" type="text" id="vida_util" class="round default-width-input" />
<label for="saldo_dep">Saldo a Depreciar</label>
<input name="saldo_dep" type="text" id="saldo_dep" class="round default-width-input" disabled />
and the function should be something like this:
saldo_dep = costo_ad / vida_util
suppose we have the following fields
<input type="number" id="field1">
<input type="number" id="field2">
<span id="label"></span>
so, you'd want to attach the jquery function to some action on the fields, like after the user finishes entering text in either of the boxes
$("#field1, #field2").keyup( function(){
var n1 = $("#field1").val();
var n2 = $("#field2").val();
var result = n2/n1;
$("#label").text(result);
});
Example is in jsFiddle... http://jsfiddle.net/A3qat/5/

Javascript Form Update Onclick

I am making an html form that will allow the user to submit numbers. Instead of having the user enter numbers, I simply want them to be able to click a button to increase or decrease the number in the text input. The following important pieces of code does this exactly how I want:
Javascript:
<script type="text/javascript">
function increase (form) {
var val = form.h1.value;
val++;
form.h1.value = val;
}
function decrease (form) {
var val = form.h1.value;
val--;
form.h1.value = val;
}
</script>
HTML
<input type="textbox" name="h1" size="3">
<input type="button" onclick="increase(this.form)" value="+">
<input type="button" onclick="decrease(this.form)" value="-">
My problem is that I want to be able to use the 'increase' and 'decrease' functions for any of the other textboxes (such as h2, h3, etc.). I tried to change the code by adding a second parameter, id, and using it to determine which form element to update. It will not work though. Any help figuring out where I went wrong would be appreciated!
Javascript
<script type="text/javascript">
function increase (form, id) {
var val = form.id.value;
val++;
form.id.value = val;
}
function decrease (form, id) {
var val = form.id.value;
val--;
form.id.value = val;
}
</script>
HTML
<input type="textbox" name="h1" size="3">
<input type="button" onclick="increase(this.form, h1)" value="+">
<input type="button" onclick="decrease(this.form, h1)" value="-">
Try
function increase (form, id) {
var val = form[id].value;
val++;
form[id].value = val;
}
and
<input type="button" onclick="increase(this.form, 'h1')" value="+">
<input type="button" onclick="decrease(this.form, 'h1')" value="-">
A form works as a dictionary where you can address its fields by name. You do this by using square brackets. The name of the field is a string, so that's why you have to pass 'h1' instead of of just h1.
Try making these changes:
In your form pass a string of the ID instead of a variable.
<input type="textbox" name="h1" size="3">
<input type="button" onclick="increase(this.form, 'h1')" value="+">
<input type="button" onclick="decrease(this.form, 'h1')" value="-">
And in your JavaScript, change the way you are referencing the field int he form.
<script type="text/javascript">
function increase (form, id) {
var val = form[id].value;
val++;
form.id.value = val;
}
function decrease (form, id) {
var val = form[id].value;
val--;
form.id.value = val;
}
</script>
Instead of passing two parameters, you can directly pass the textbox element whose value needs to be changed. Try below changes.
<input type="textbox" name="h1" size="3">
<input type="button" onclick="increase(document.h1)" value="+">
<input type="button" onclick="decrease(document.h1)" value="-">
And your javascript functions will be like below.
<script type="text/javascript">
function increase (element) {
element.value = element.value++;
}
function decrease (element) {
element.value = element.value--;
}
</script>

Categories

Resources