HTML javascript function issue. [object HTMLInputElement] error output - javascript

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>

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;

Calculator with Javascript and 2 fields

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>

JavaScript string concatenation not working

This javascript code to concatenate isn't working. I tried an alert before closure of script tag, it's displayed but the code below that I want to display the result in third or different text field.
HTML:
<input type="text" id="field"><br>
<input type="text" id="str2"><br>
<input type="text" id="str3"><br>
<button onclick="concate()">Concatenate</button>
JavaScript:
var s=document.getElementById("field").value;
var t=document.getElementById("str2").value;
var st=document.getElementById("str3").value;
function concate()
{
st=s+t;
document.getElementById("str3").value.innerHTML=st;
console.log(st);
document.write(st);
}
There's no function .value.innerHTML should be :
document.getElementById("str3").value = st;
Also you should get the fields value inside function and close your function definition using }, check example bellow.
Hope this helps.
function concate()
{
var s=document.getElementById("field").value;
var t=document.getElementById("str2").value;
document.getElementById("str3").value=s+t;
}
<input type="text" id="field"><br>
<input type="text" id="str2"><br>
<input type="text" id="str3"><br>
<button onclick="concate()">Concatenate</button>
function concate() {
var s=document.getElementById("field").value;
var t=document.getElementById("str2").value;
var st=document.getElementById("str3").value;
// this is a standard way to concatenate string in javascript
var result = s+t;
document.getElementById("str3").value=result;
}
<input type="text" id="field"><br>
<input type="text" id="str2"><br>
<input type="text" id="str3" readonly><br>
<button onclick="concate()">Concatenate</button>

dividing user entered data in javascript

here are the instructions I was given:
Include 2 textboxes for user to enter 2 numbers. Advise user to enter 0 in
the second textbox so you can display the results of division by 0. Advise
user to enter a string to see the result. The first operation is to see the
result of division by 0. The second operation is to see the result of using a
text string in a mathematical operation. Button – call the function and
display the result
my html:
<form>
Enter a number: <input type="number" id="number_box_1">
Enter a number: <input type="text" id="number_box_2">
<input type="button" value="Does Something" id="does_something" onclick="Division()">
<input type="reset">
results: <input type="text" id="math_results">
</form>
my javascript:
function Division(){
var number_1 = document.getElementById("number_box_1").value;
var number_2 = document.getElementById("number_box_2").value;
// textbox where results will be shown
var results_shown = document.getElementById("math_results").value;
results_shown = number_1/number_2;
}
I have tried several things but havent gotten it to work. I think I may need to use parseint() but even after some reading, I still not sure how to write it into my function, or if that would be the correct thing to use. I fell like theres something i should be using but unsure. what should I be using to be able to divide number_box_1 by number_box_2?
Instead of:
var results_shown = document.getElementById("math_results").value;
results_shown = number_1/number_2;
You have to use:
document.getElementById("math_results").value = number_1/number_2;
Runnable example:
function Division(){
var number_1 = document.getElementById("number_box_1").value;
var number_2 = document.getElementById("number_box_2").value;
// textbox where results will be shown
document.getElementById("math_results").value = number_1/number_2;
}
<form>
Enter a number: <input type="number" id="number_box_1">
Enter a number: <input type="text" id="number_box_2">
<input type="button" value="Does Something" id="does_something" onclick="Division()">
<input type="reset">
results: <input type="text" id="math_results">
</form>
You were storing the value of the result input instead of a reference to it, so you were just modifying a variable and not the actual value.
function Division(){
var number_1 = document.getElementById("number_box_1").value;
var number_2 = document.getElementById("number_box_2").value;
// textbox where results will be shown
var result = document.getElementById("math_results");
result.value = number_1/number_2;
}
<form>
Enter a number: <input type="number" id="number_box_1">
Enter a number: <input type="text" id="number_box_2">
<input type="button" value="Does Something" id="does_something" onclick="Division()">
<input type="reset">
results: <input type="text" id="math_results">
</form>
However, I would do something like this.
var box1 = document.getElementById("number_box_1");
var box2 = document.getElementById("number_box_2");
var result = document.getElementById("math_results");
var form = document.getElementById("form");
form.onsubmit = function(e) {
e.preventDefault(); // To disallow the form's submission
result.value = box1.value/box2.value;
}
label { display: block; }
<form id="form">
<label>Enter a number: <input type="number" id="number_box_1" required></label>
<label>Enter a number: <input type="text" id="number_box_2" required></label>
<label>results: <input type="text" id="math_results" readonly></label>
<div><input type="reset"> <input type="submit" value="Evaluate"></div>
</form>
You have to put the result into the .value property. Right now you are assigning it to the results_shown variable.
Also, you have to be careful with forms, or it might cause a page post which would appear to knock out the results.
You cannot have the errors like division by 0 or division by string based on the responses coming you have to manually check what is the results_shown and then output to the result input box.
But I guess this is the start point.
function Division(){
var number_1 = document.getElementById("number_box_1").value;
var number_2 = document.getElementById("number_box_2").value;
// textbox where results will be shown
var results_shown;
try{
results_shown = parseInt(number_1)/parseInt(number_2);
}catch(e){
results_shown = e;
}
document.getElementById("math_results").value = results_shown;
}
<form>
Enter a number: <input type="number" id="number_box_1">
Enter a number: <input type="text" id="number_box_2">
<input type="button" value="Does Something" id="does_something" onclick="Division()">
<input type="reset">
results: <input type="text" id="math_results">
</form>

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

Categories

Resources