Javascript and mathjax ascii - javascript

I have a problem, I want to add numbers using a 'textbox' to add my formula math, but it won't render it
<p style="text-align:center; font-size:40px;">
`int ax^n dx `
</p>
Input nilai a : <input type="text" id="a" value="10">
Input nilai n : <input type="text" id="n" value="5">
<button onclick="coba()">OK</button>
<div id="tampil"></div>
<script>
function coba(){
var a= document.getElementById("a").value;
var n= document.getElementById("n").value;
var e= "`int"+ a +"x^"+ n + "dx`"
var f= a+n;
document.getElementById("tampil").innerHTML= e;
}
</script>

You need to tell MathJax that new math has been added to the page after you set the innerHTML. Do that by adding
MathJax.Hub.Queue(["Typeset",MathJax.Hub,"tampil"]);
after you set the innerHTML.
See the documentation for more details.

Related

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

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>

Cant add input and display the sum in JavaScript

To learn and study JavaScript, im trying to do a calculator, and as start i tried to do a sum operation by taking 2 input. But somehow there is a problem that i cant see. Can you help me?
Here is the code:
<html>
<body>
<h1> JavaScript Test </h1>
Sum The Nums Up!
<br>
<form>
Number 1: <input type="text" name="n1" /><br>
Number 2: <input type="text" name="n2" /><br>
</form>
<button id="b" onclick="func();" />Sum</button>
<p id="b"></p>
<script type="text/javascript">
function sum() {
var nn1 = document.getElementById("n1").value;
var nn2 = document.getElementById("n2").value;
var sum = parseInt(nn1) + parseInt(nn2);
document.write(sum);
}
</script>
</body>
</html>
Replace:
function sum() {
With:
function func() {
This prevents you from assigning 2 different types / values to the same variable name.
(You've got an sum function and a sum variable in your question.)
Replace:
document.write(sum);
With
document.getElementById('b').innerHTML = sum;
This snippet adds the result of sum to <p id="b"></p> (So, the result may be: <p id="b">18</p>, for example), instead of arbitrarily adding it to the end of your HTML.
And finally, replace:
Number 1: <input type="text" name="n1"/><br>
Number 2: <input type="text" name="n2"/><br>
With:
Number 1: <input type="text" id="n1"/><br>
Number 2: <input type="text" id="n2"/><br>
document.getElementById looks for the id attribute in your HTML, not for the name.
There are two problems:-
Change onclick="func();" to onclick="sum();" , you are calling the wrong/undefined function.
<button id="b" onclick="sum();"/>Sum</button>
Assign input tags id as n1 and n2, you have assigned them as name and are referring to them based on id getElementById()
Number 1: <input type="text" id="n1"/><br>
Number 2: <input type="text" id="n2"/><br>
<html>
<body>
<h1> JavaScript Test </h1>
Sum The Nums Up!
<br>
<form>
Number 1: <input type="text" id="n1" name="n1"/><br>
Number 2: <input type="text" id="n2" name="n2"/><br>
</form>
<button id="b" onclick="sum();"/>Sum</button>
<p id="b"></p>
<script type="text/javascript">
function sum()
{
var nn1 = document.getElementById("n1").value;
var nn2 = document.getElementById("n2").value;
var sum = parseInt(nn1) + parseInt(nn2);
document.write(sum);
}
</script>
</body>
</html>

form won't display value after calculation in javascript

i am trying to do some calculation but it does not seem to work.
I need to perform calculations on the data the user inputs and then display the results.
I don't seemed to be able to get the output for b and c. Is there a difference if i divide by a decimal/decimal?
<script type="text/javascript">
function myFunction() {
var x = document.getElementById("energycost").value;
var y = document.getElementById("peak").value;
var z = document.getElementById("nonpeak").value;
var k = document.getElementById("input").value;
var b = x / (y + (z / k));
var c = b / k;
document.convert.output1.value = b;
document.convert.output2.value = c;
}
</script>
<body>
<FORM ACTION="#" NAME="convert">
Step 1:<br>
Enter the Fixed Tariff cost($/kWh)
<input type="text" id="fixed"SIZE=6
onblur="multiply.call(this,this.form.elements.energyload.value,this.form.elements.fixed.value)">
Enter the Total Energy load value(kWh)
<input type="text" id="energyload"SIZE=6
onblur="multiply.call(this,this.form.elements.energyload.value,this.form.elements.fixed.value)">
<BR><BR>
Total Energy load cost($)
<input type="text" id="energycost"SIZE=6 DISABLED>
<BR><BR>
Step 2: <br>
Enter Total Peak Energy load value(kWh)
<input type="text" id="peak"SIZE=6>
Enter Total Non-Peak Energy load value(kWh)
<input type="text" id="nonpeak"SIZE=6>
<BR><BR>
Step 3:<br>
Enter K value
<input type="text" id="input"SIZE=4
ONKEYUP="myFunction()">
<BR><BR>
<input type="text" id="output1" DISABLED>
TOU Peak Price
<input type="text" id="output2" DISABLED>
TOU Non-Peak Price
</FORM></body>
I don't really see where your result comes from.
This could be the solution (though I didn't try it, keep me posted):
document.convert.output1.value = b
document.convert.output2.value = c
I'd parseInt() on those values or do some validation on the user input, and as pointy added,
document.convert.output1.value = b;

Get numerical values from input fields and use them to calculate the surface area of a trapezoid

I am new to Javascript and I will be thankful if someone help me understand what I am doing wrong. I am trying to calculate the surface area of a trapezoid by obtaining values from input fields. When I press the "Calculate S" button I get a "Nan" as an answer.
This is the major part of the HTML code:
<form method="post">
<label for="a">a</label>
<input type="text" id="a"/> <br/>
<label for="b">b</label>
<input type="text" id="b"/> <br/>
<label for="h">h</label>
<input type="text" id="h"/> <br/>
<button onclick="alert(S)">Calculate S</button>
</form>
And this is the script I am using to obtain the values and calculate the surface:
<script type="text/javascript">
var a=parseInt(document.getElementById("a"), 10);
var b=parseInt(document.getElementById("b"), 10);
var h=parseInt(document.getElementById("h"), 10);
var S=parseInt(((a+b)/2)*h, 10);
</script>
Thanks in advance!
You need to get the value out of each input, not just the input, like this:
<script type="text/javascript">
var a=parseInt(document.getElementById("a").value, 10);
var b=parseInt(document.getElementById("b").value, 10);
var h=parseInt(document.getElementById("h").value, 10);
var S=((a+b)/2)*h;
</script>
Use .value property on the input elements to get their contents. then call parseInt on that to get a number.
No need to parseInt the result too.
var S = ((a + b) / 2) * h;
Wrap the code in a callable function if you want it executed on button click (what you have now will execute when the code been parsed by your browser).
Example found here: http://jsfiddle.net/bpwEh/
Updated code:
<head>
<!-- ... -->
<script>
function calc(){
var a=parseInt(document.getElementById("a").value, 10);
var b=parseInt(document.getElementById("b").value, 10);
var h=parseInt(document.getElementById("h").value, 10);
return ((a+b)/2)*h, 10;
}
</script>
</head>
<body>
<form method="post">
<label for="a">a</label>
<input type="text" id="a"/> <br/>
<label for="b">b</label>
<input type="text" id="b"/> <br/>
<label for="h">h</label>
<input type="text" id="h"/> <br/>
<button onclick="alert(calc()); return false;">Calculate S</button>
</form>
</body>

Categories

Resources