Calculator with Javascript and 2 fields - javascript

I am supposed to make a calculator (it's supposed to be done by tomorrow) and it's in Javascript and I am taking this distance course and they've just introduced Javascript with this assignment and I don't understand any of the code and what it means. I understand HTML and CSS but JS is just something I don't understand at all.
I have gotten started on the code but I cannot get any further because I can't find anything online of a calculator like this or any easy explanation of JS. It is supposed to not have a submit-button and the design is irrelevant but it's supposed to have two text fields.
function Calculate() {
var number1 = document.getElementById("number1").value;
var number2 = document.getElementById("number2").value;
number1_parsed = parseInt(tal1);
tal2_parsed = parseInt(tal2);
if (number1_parsed) {} else
alert("Wrong characters");
return false;
} {
summa = number1_parsed + number2_parsed;
alert("Sum" + sum);
}
<div id="calculator">
<h1> Calculator </h1>
<form name="kalkylator">
<input type="text" name="number1" id="number1" size="10" />
<input type="text" name="number2" id="number2" size="10" />
<input type="button" onclick="Calculate();" id="calculate" value="Result">
</form>
</div>

You need to keep your code clearly formatted. It helps simplify debugging. Keep your indentation accurate. Had you done this you would probably have seen the messed up curly braces.
Also you were inconsistent in your variable names.
For example:
You have no open curly brace ({) after your else
You have a random open curly brace before this line: summa = number1_parsed + number2_parsed;
You call parseInt(tal1); but your variable is number1 and not tal1
You use summa to hold the sum, but your alert uses sum
var number1 = document.getElementById("number1");
var number2 = document.getElementById("number2");
function Calculate() {
var number1_parsed = parseInt(number1.value);
var number2_parsed = parseInt(number2.value);
if (isNaN(number1_parsed) || isNaN(number2_parsed)) {
alert("Wrong characters");
return false;
}
var sum = number1_parsed + number2_parsed;
alert("Sum: " + sum);
}
<div id="calculator">
<h1> Calculator </h1>
<form name="kalkylator">
<input type="text" name="number1" id="number1" size="10" />
<input type="text" name="number2" id="number2" size="10" />
<input type="button" onclick="Calculate();" id="calculate" value="Result">
</form>
</div>

Related

Converting a value using JavaScript

Somehow my below JavaScript code to convert the value from kilometers to nautical mile doesn't seem to work. It seems very simple but I could not find out why I am. I would appreciate your help.
<div class="calculator">
<form>
Enter a value in Kilometers:
<input type="text" id="kM" value="1000"> Result in Nautical Mile:
<input type="text" id="nM" value="" disabled>
<button onclick="return calculate();" id="calculate">CALCULATE</button>
</form>
</div>
<script>
function convert(kiloMeter) {
return kiloMeter / 1.852;
}
function calculate() {
var kMeter = Number(document.getElementById("kM").value);
var convertedValue = convert(kMeter);
document.getElementById("nM").innerHTML =
convertedValue;
return false;
}
</script>
There are at least two issues causing your script to not work
Input elements don't have an innerHMTL property. They have a value. So document.getElementById("nM").innerHTML should be document.getElementById("nM").value
At that point everything should be fine. You shouldn't need to change your button type to button since you return false from the function and the button returns false to the form, stopping the form from submitting. HOWEVER there appears to be an issue with naming your function calculate (at least in Chrome and Firefox) the same as the id of the element (id="calculate"). Changing the name of the function or the id fixes the issue.
function convert(kiloMeter) {
return kiloMeter / 1.852;
}
function calculate() {
var kMeter = Number(document.getElementById("kM").value);
var convertedValue = convert(kMeter);
document.getElementById("nM").value = convertedValue;
return false;
}
<div class="calculator">
<form>
Enter a value in Kilometers:
<input type="text" id="kM" value="1000"> Result in Nautical Mile:
<input type="text" id="nM" value="" disabled>
<button onclick="return calculate();" id="xcalculate">CALCULATE</button>
</form>
</div>
For input tag you should use value rather than innerHtml. You do not need to return false also.
<div class="calculator">
<form>
Enter a value in Kilometers:
<input type="text" id="kM" value="1000"> Result in Nautical Mile:
<input type="text" id="nM" value="" disabled>
<button type='button' onclick="calculate()" id="">CALCULATE</button>
</form>
</div>
<script>
function convert(kiloMeter) {
return kiloMeter / 1.852;
}
function calculate() {
var kMeter = Number(document.getElementById("kM").value);
var convertedValue = convert(kMeter);
document.getElementById("nM").value =
convertedValue;
}
</script>
You should use value instead of innerHTML:
document.getElementById("nM").value = convertedValue;

An invalid form control with name='' is not focusable with type=number and decimal numbers

I know this topic has been quite active in SO, but now I seem to have found something strange with input fields with type="number" and decimal numbers. My code is something like this:
function Sum(){
var f = document.myform;
var num1 = f.num1.value;
if (isNumber(num1)){
alert(parseFloat(num1));
}
}
function isNumber(n) {
return (!isNaN(parseFloat(n)) && isFinite(n) && n >= 0);
}
#num1 {
display:none;
}
<form name="myform" enctype="application/x-www-form-urlencoded" action="javascript:void(0);">
<input id="num1" type="number" value="1.5">
<input id="run_button" class="button" type="submit" onclick="Sum()"/>
</form>
Every time I put decimal numbers in number fields, I get this error, but if the numbers are without the dot, the error does not appear. You can test in test form.
This solved my problem
<input type='number' min='0' step='Any'/>

calculate values using entered formula

This is my html code:
<input id="R1" type="text" value="100">
<input id="R2" type="text" value="200">
<input id="formula" type="text" value="">
<input type="button" id="save" value="save">
Here the user enter formula value dynamically like R1+R2, (R1-R2)*100. I need to calculate final value using the formula.
Ex: If user enter value in formula field R1+R2; I need the result 300.
How do I calculate the value dynamically?
Check out this snippet, should work with any combo:
function calExpression() {
var f = document.getElementById('formula');
var inps = document.getElementsByTagName('input');
var expression = f.value.toUpperCase();//' '+f.value.replace(/([-\/\+\(\)])/g,' $1 ')+' ';
for (var i = 0; i < inps.length; i++) {
if (inps[i].id && inps[i].type && inps[i].type.toLowerCase() === 'text') {
expression = expression.replace(new RegExp('\\b'+inps[i].id+'\\b', 'ig'), inps[i].value);
}
}
eval('f.value = '+expression+';');
}
<input id="R1" type="text" value="100">
<input id="R2" type="text" value="200">
<input id="formula" type="text" value="">
<input type="button" id="save" value="save" onclick="calcExpression()">
You can use eval. This is the fastest and easiest solution, but you must be careful with it and check with regexp that formula has only R1, R2, (, ) and math operators in it.
Or (better solution) you can find a library to parse expressions, in example http://mathjs.org/docs/expressions/parsing.html
<input type="button" id="save" value="save" onclick="return calculate()">
<script>
function calculate() {
var val1 = document.getElementById('R1').value;
var val2 = document.getElementById('R2').value;
var result = +val1 + +val2;
document.getElementById('formula').value = result;
}
</script>
Because a problem occures with "+" you have to use +val1 + +val2
Infix to Prefix Conversion Algorithm:
Infix to Prefix Conversion
Prefix Evaluation Algorithm:
Prefix Evaluation Algorithm
Use help from these links.
You can use .eval() method which allow you to evaluates JavaScript code represented as a string. It's a really powerful method.
Then, you have to parse your formula. With this piece of code, you will be able to add expression like ((R1+R2) - (R1*3)) + 1 for example.
function calculate(){
var valid = true;
var regex = /(?:[a-z$_][a-z0-9$_]*)|(?:[;={}\[\]"'!&<>^\\?:])/ig;
var formula = document.querySelector('#formula').value;
var R1 = parseInt(document.querySelector('#R1').value);
var R2 = parseInt(document.querySelector('#R2').value);
formula = formula.replace(/R1/g, R1).replace(/R2/g,R2);
formula = formula.replace(regex, function (elm) {
return Math.hasOwnProperty(elm)
? "Math."+elm
: valid = false;
});
if (valid)
alert(eval(formula));
}
Then add onlick event on save button :
<input id="R1" type="text" value="100">
<input id="R2" type="text" value="200">
<input id="formula" type="text" value="">
<input type="button" id="save" value="save" onclick="calculate()">
Here is the Working Plunker

Multiplying calculator

I am trying to create a simple calculator that takes a number from 1 text box and after hitting a submit button it takes the number and multiplies it by 92 then puts it in a read only box.
This is what I have so far:
<form name="1star">
<input type="text" name="input"/>
<input type="button" value="Enter" OnClick="1star.output.value == 1star.input.value * 92"/>
<br/>
<input type="text" name="output" readonly="readonly" />
</form>
This is not working and I could use some help. I know its easy but I am very new to js and I'm not understanding why this isn't working.
<form name="onestar">
<input type="text" name="input"/>
<input type="button" value="Enter" OnClick="onestar.output.value = onestar.input.value * 92"/>
<br/>
<input type="text" name="output" readonly="readonly" />
</form>
An identifier cannot start with a digit in JavaScript, so 1star is an error. Also, you wanted = (assignment), not == (comparison).
That said, there are a number of outdated or beginner practices above. If I was writing it, I would separate the script from the markup, and I'd use document.getElementById to fetch the element rather than relying on implicit variables defined by name. I would also explicitly parse the string into a number. But for now no need to worry about it too much. Even though the code seems much more complicated at first glance, it's all things that will make your life easier later, with bigger programs.
var input = document.getElementById('input');
var output = document.getElementById('output');
var button = document.getElementById('button');
button.addEventListener('click', function(evt) {
var value = parseInt(input.value, 10);
if (!isNaN(value)) {
output.value = value * 92;
}
});
<form>
<input type="text" id="input"/>
<input type="button" id="button" value="Enter"/>
<br/>
<input type="text" id="output" readonly="readonly" />
</form>

HTML javascript function issue. [object HTMLInputElement] error output

I am trying to make a simple html page with two text boxes and an a button that adds the two numbers together when clicked. In my output, I am only getting [object HTMLInputElement].
function addNumbers(A, B){
var answer = A + B;
document.getElementById("testResult").innerHTML = answer;
}
<input type="text" value="15" id="varA">
<input type="text" value="30" id="varB">
<input type="button" value="Add" onclick="addNumbers(varA, varB)">
<h1 id="testResult"></h1>
Any help would be appreciated. I tried changing .innerHTML to .value already but then I get nothing at all as a result.
I assume you want the mathematical sum and not the string concatenation. If that's the case, you can use the following:
UPDATE based on comment:
function addNumbers(elem1, elem2) {
var a = document.getElementById(elem1).value;
var b = document.getElementById(elem2).value;
var c = Number(a) + Number(b);
document.getElementById("testResult").innerHTML = c;
}
<input type="text" value="15" id="varA">
<input type="text" value="30" id="varB">
<input type="button" value="Add" onclick="addNumbers('varA', 'varB')"></input>
<h1 id="testResult"></h1>
Here's a working Fiddle: http://jsfiddle.net/JohnnyEstilles/ex09fx7k/.
Some fixes:
You are adding up the inputs elements instead of their value.
To convert its string value to a number, you can use unary +.
Instead of inline event listeners, better use addEventListener.
var a = document.getElementById('varA'),
b = document.getElementById('varB'),
result = document.getElementById("testResult");
document.getElementById('add').addEventListener('click', function() {
addNumbers(a.value, b.value);
});
function addNumbers(n1, n2){
result.textContent = +n1 + +n2;
}
<input type="text" value="15" id="varA">
<input type="text" value="30" id="varB">
<input type="button" id="add" value="Add">
<h1 id="testResult"></h1>

Categories

Resources