I am working on making a simple interest calculator but I keep getting Not a Number:
<script type="text/javascript">
function intcal() {
var pr=document.getElementById("P");
var ra=document.getElementById("r");
var ti=document.getElementById("t");
var interest=pr*ra*ti;
document.write(interest);
}
</script>
<h1> Principal </h1>
<Input type="number" id="P" name="Principal" Size="16">
<h1> Rate </h1>
<Input type="number" id="r"name="Rate" Size="16">
<h1> Time </h1>
<Input type="number" id="t" name="Time" Size="16">
<input type="button" onClick=intcal() value="Calculate">
A few problems there. getElementById returns a DOM element. You need to grab the value of the element, which is a string, and then convert it to a number (or cast it):
var pr = +document.getElementById("P").value;
var ra = +document.getElementById("r").value;
var ti = +document.getElementById("t").value;
+ casts the string to a number. Now your multiplication should work.
Also you forgot your quotes around the function call on the onclick event. Oh and read on why document.write is bad practice.
Edit: As Bergi said, multiplication casts a number as well, but in any case since you have variables, you probably want numbers assigned to them.
Related
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
So I am fairly new to Javascript, and I am working on some code that converts decimal numbers to binary numbers. However when I run this program, I can't seem to get the output I am looking for. The best I have done was get my function to output an exact number already inside of the function, when I am instead trying to get an output that is generated from any number typed into the textbox? I'm not entirely sure where I am going wrong with this. I feel like there is something I am clearly missing, but I can't seem to grasp exactly what it is. I've been using codecademy and w3schools to gain more knowledge of JavaScript, but if anyone has any other resources that helped them when they first started programming that would be great!
<!DOCTYPE html>
<html>
<body>
<p>Convert from Decimal to Binary:</p>
<form method = "post">
<p id = "demo">
<label for="decNum"></label>
<input name="decNum" type="text">
<button onclick="toBinary()">Enter</button>
</p>
</form>
<script>
function toBinary() {
document.getElementById("demo").innerHTML =
parseInt(num,10).toString(2);
}
</script>
</body>
</html>
It's because num doesn't have a value.
Try this:
<p>Convert from Decimal to Binary:</p>
<form method = "post">
<p id = "demo">
<label for="decNum"></label>
<input name="decNum" type="text" id="decNum">
<button onclick="toBinary()">Enter</button>
</p>
</form>
<script>
function toBinary() {
var num = document.getElementById("decNum").value;
document.getElementById("demo").innerHTML =
parseInt(num, 10).toString(2);
}
</script>
There are a few things I would change. First off, I would keep non form elements outside of the form. The major issue is that num doesn't have a value, but to ensure it works you will also want to take the event and use event.preventDefault() to make sure it doesn't submit the form. Try:
<!DOCTYPE html>
<html>
<body>
<p>Convert from Decimal to Binary:</p>
<form method="post">
<label for="decNum"></label>
<input id="field" name="decNum" type="text">
<button onclick="toBinary(event)">Enter</button>
</form>
<p id="demo"></p>
<script>
function toBinary(event) {
event.preventDefault();
var value = document.getElementById('field').value;
document.getElementById("demo").innerHTML =
parseInt(Number(value), 10).toString(2);
}
</script>
</body>
</html>
You're not defining num.
Grab it from the input as such:
function toBinary() {
const num = document.getElementById("textInput").value;
document.getElementById("demo").innerHTML = parseInt(Number(num),10).toString(2);
}
<p id = "demo"></p>
<label for="decNum"></label>
<input name="decNum" type="text" id="textInput">
<button onclick="toBinary()">Enter</button>
I am currently experimenting with simple addition by adding the values of three input elements.
I have three input elements and a button element with an onclick listener to invoke my function. The function is to simply return the output of the sum of those values inputted by the user in an h2 element, and that is all. Here are the HTML and JS:
<div class="inputFields">
<input class="lado" type="text" />
<input class="lado" type="text" />
<input class="lado" type="text" />
</div>
<button type="button" onclick="getArea()">click</button>
<h2 id="areaResult"></h2>
var s1 = document.getElementsByClassName('lado')[0].value;
var s2 = document.getElementsByClassName('lado')[1].value;
var s3 = document.getElementsByClassName('lado')[2].value;
/*to my understanding, the .value property (like .innerHTML) renders a
string value. Do please correct me if I'm wrong.*/
function getArea() {
document.getElementById('areaResult').innerHTML =
Number(s1) + Number(s2) + Number(s3);
/*Utilized Number() method to convert the string values rendered by
the .value properties to number values so as to perform addition
arithmetic operation rather than concatenation.*/
}
The output for some mysterious reason to me however is always 0 no matter what numbers I input or even if I input non-numerical characters.
What am I doing wrong?
Declare all the variables inside the function.
You do not need to write document.getElementsByClassName every time. Simply use a variable to store all the class element then use index to get the value from that variable like the following:
function getArea() {
var lado = document.getElementsByClassName('lado');
var s1 = lado[0].value;
var s2 = lado[1].value;
var s3 = lado[2].value;
document.getElementById('areaResult').innerHTML =
Number(s1) + Number(s2) + Number(s3);
}
<div class="inputFields">
<input class="lado" type="text" />
<input class="lado" type="text" />
<input class="lado" type="text" />
</div>
<button type="button" onclick="getArea()">click</button>
<h2 id="areaResult"></h2>
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
Context: I have a text field in my form that is meant for entering an amount of money. I want variables for dollars and cents. Can javascript find the location of the decimal point, and separate it into two integers?
"$111.01".split('.'); yields ['$111', '01']
Then it's a matter of cleaning that up (.replace) and coercing them into ints (parseInt).
here i such Example:
http://jsfiddle.net/9FDrN/1/
HTML:
<script type='text/javascript' src='https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js'></script>
<input type="text" id="amount" value="$100.01">
<input type="text" id="dollars" value=""><br/>
<input type="text" id="cents" value=""><br/>
JS:
$(document).ready(function(){
var amount_val = $("#amount").val();
var out = amount_val.split(".");
$("#dollars").val(out[0].replace("$",""));
$("#cents").val(parseInt(out[1],10));
});