calculate values using entered formula - javascript

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

Related

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>

Changing innerHTML to value from div's Id captured by it's ClassName

I have some buttons 1-9 and i want to show their numbers on div called "screen". So i wrote such code, but it not seem to work.
Piece of HTML code with those buttons:
<div id="screen"></div>
<div><input type="submit" class="numKey" id="key7" value="7" onclick="enterPIN();"></div>
<div><input type="submit" class="numKey" id="key8" value="8" onclick="enterPIN();"></div>
<div><input type="submit" class="numKey" id="key9" value="9" onclick="enterPIN();"></div>
<div style="clear: both;"></div>
<div><input type="submit" class="numKey" id="key4" value="4" onclick="enterPIN();"></div>
<div><input type="submit" class="numKey" id="key5" value="5" onclick="enterPIN();"></div>
(... AND SO ON ...)
JavaScript code:
function enterPIN()
{
for (i=0; i<document.getElementsByClassName("numKey").length; i++)
{
var numKeyId = i + " " + document.getElementsByClassName("numKey")[i].id;
console.log(numKeyId);
return numKeyId;
}
var getElementId = function(numKeyId)
{
this.numKeyId = numKeyId;
document.getElementById("screen").innerHTML = document.getElementsByClassName("numKey")[numKeyId].id;
console.log("Asdasdasd");
}
getElementId();
}
It should work like this:
The first time the for loop iterates (with i=0), it will get to the return statement and the function will quit after just one iteration never reaching the last part of the script.
This can be done with less code if you just change the HTML a little bit by putting the value as an argument to enterPin:
<input type="button" class="numKey" id="key7" value="7" onclick="enterPIN(7);">
Or, as suggested by bcdan, by using this so you don't have to repeat yourself:
<input type="button" class="numKey" id="key7" value="7" onclick="enterPIN(this.value);">
Do note that I changed from submit to button since you do not actually want to submit the form once the buttons are pressed. Then you just need this JS:
function enterPin(number) {
screen = document.getElementById("screen");
screen.innerHTML = screen.innerHTML + String(number);
}
Or, if you want to use jQuery (and get rid of the onclick attribute):
$(".numKey").click(function() {
screen = $("#screen");
screen.html(screen.html + this.value);
});
Well if you just need it to output what you click, why not do something like
<html>
<body>
<script>
function enterPIN(value)
{
document.getElementById('screen').innerHTML += String(value);
}
</script>
<div id="screen"></div>
<div><input type="submit" class="numKey" id="key7" value="7" onclick="enterPIN(this.value);"></div>
<div><input type="submit" class="numKey" id="key8" value="8" onclick="enterPIN(this.value);"></div>
<div><input type="submit" class="numKey" id="key9" value="9" onclick="enterPIN(this.value);"></div>
</body>
</html>
Look at this example
window.onload = function(){
var MAX_LEN = 4,
currentValue = "",
elScreen = document.getElementById('screen'),
addDigit = function(digit){
digit = digit instanceof MouseEvent ? this.value : digit;
if (elScreen.innerHTML.length < MAX_LEN) elScreen.innerHTML += digit;
},
delDigit = function(){
elScreen.innerHTML = elScreen.innerHTML.slice(0,elScreen.innerHTML.length - 1);
};
//setting handlers for numKeys
numBtns = document.getElementsByClassName('numKey');
for (var i = 0 ; i < numBtns.length; i++) numBtns[i].onclick = addDigit;
//setting handler for backKey
document.getElementById('backKey').onclick = delDigit;
}
Do not think about event handlers first. Write simple functions addDigit and delDigit, and after call them from handlers.
The simplest solution is to pass this.value in the onclick function parameters (as #DanielBeck suggests):
<input type="button" value="1" onclick="enterPIN(this.value)"/>
This is much simpler than trying to pull out which button was pressed, when that information can be directly delivered.

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>

jQuery selectors - more elegant solution

Given the following HTML fragment:
<div class="word">
<input type="text" name="A" />
<input type="text" name="n" />
</div>
<div class="word">
<input type="text" name="E" />
<input type="text" name="x" />
<input type="text" name="a" />
<input type="text" name="m" />
<input type="text" name="p" />
<input type="text" name="l" />
<input type="text" name="e" />
</div>
I'd like to write a jQuery script that would concatenate all the ':text' elements' names in a single string, while adding a space when reaching the end of a 'div.word' element.
For example, given the HTML above, the result would be:
An Example
Using my (very) limited jQuery/javascript skills I managed to find a solution, but it involves dirty for ... in loops, so I'd rather not show it here :-).
I'd like to know what is a more elegant/idiomatic (and probably more concise) solution to this problem.
Here's a DEMO: http://jsfiddle.net/ZRukk/1/
var string = $('.word input').map(function() {
var is_last = $(this).is(':last-child');
return this.name + (is_last ? ' ' : '');
}).toArray().join('');
In modern browsers, you could do it without jQuery like this...
Here's a DEMO: http://jsfiddle.net/ZRukk/4/
var inputs = document.querySelectorAll('.word input');
var string = [].map.call(inputs, function(el) {
return el.name + (!el.nextElementSibling ? ' ' : '');
}).join('');
You can do it like this:
var result = [];
$('.word').each(function() {
$(this).find('input').each(function() {
result.push(this.name);
});
result.push(' ');
});
var answer = $.trim(result.join(''));
Working example here: http://jsfiddle.net/jfriend00/DNWSm/
And, a slightly different way of doing it that is probably faster because it's probably less DOM searching:
var result = [];
var lastParent;
$('.word input').each(function() {
// if starting a new parent, add a word separator
if (lastParent && lastParent != this.parentNode) {
result.push(' ');
}
result.push(this.name);
lastParent = this.parentNode;
});
var answer = result.join('');
Working example here: http://jsfiddle.net/jfriend00/bEBGQ/

Categories

Resources