Javascript Text Input Calculator - javascript

I am somewhat new to Javascript and I'm trying to make a basic calculator that has 3 text inputs, a 1st number text box, an operation textbox, and a second number textbox, but it doesn't print out the text when I click a button or use any other method to trigger the event.
This is my code:
<html>
<script>
function calc()
{
var D = "";
var A = document.getElementById("num1").value;
var B = document.getElementById("op").value;
var C = document.getElementById("num2").value;
if(B == "+")
{
D = A+C;
}
elseif(B == "-")
{
D = A-C;
}
elseif(B == "*")
{
D = A*C;
}
elseif(B == "/")
{
D = A/C;
}
document.getElementById("result").innerHTML = D;
}
</script>
<body>
<input type="text" id="num1" name="num1" />
<input type="text" id="op" name="op" />
<input type="text" id="num2" name="num2" />
<br />
<input type="button" value="Solve" onclick="calc()" />
<p id="result" name="r1">
<br />
</p>
</body>
</html>

I'd suggest the following (explanations commented in the code itself):
function calc() {
/* finds out whether the browser uses textContent (Webkit, Opera, Mozilla...)
or innerText (Microsoft) to set the text of an element/node */
var textType = Node.textContent ? 'textContent' : 'innerText',
/* uses parseFloat to create numbers (where possible) from the entered value
if parseFloat fails to find a number (it's empty or nonsensical)
then a 0 is used instead (to prevent NaN being the output). */
num1 = parseFloat(document.getElementById('num1').value) || 0,
num2 = parseFloat(document.getElementById('num2').value) || 0,
// retrieves the result element
result = document.getElementById('result');
// switch is used to avoid lots of 'if'/'else if' statements,
// .replace() is used to remove leading, and trailing, whitespace
// could use .trim() instead, but that'd need a shim for (older?) IE
switch (document.getElementById('op').value.replace(/\s/g,'')){
// if the entered value is:
// a '+' then we set the result element's text to the sum
case '+':
result[textType] = num1 + num2;
break;
// and so on...
case '-':
result[textType] = num1 - num2;
break;
case '*':
result[textType] = num1 * num2;
break;
case '/':
result[textType] = num1 / num2;
break;
// because people are going to try, give a default message if a non-math
// operand is used
default:
result[textType] = 'Seriously? You wanted to try math with that operand? Now stop being silly.'
break;
}
}
JS Fiddle demo.
References:
parseFloat().
switch () {...}.

I would have done things a bit differently, but to answer your question and just get your code working I did the following:
Here is your reworked code:
<html>
<script>
function calc(form) {
var D = "0";
var A = document.getElementById("num1").value;
var B = document.getElementById("op").value;
var C = document.getElementById("num2").value;
if (B === "+")
{
D = parseInt(A)+parseInt(C);
}
else if(B === "-")
{
D = parseInt(A)-parseInt(C);
}
else if(B === "*")
{
D = parseInt(A)*parseInt(C);
}
else if (B === "/")
{
D = parseInt(A)/parseInt(C);
}
document.getElementById("result").innerHTML = D;
return false;
}
</script>
<body>
<input type="text" id="num1" name="num1" />
<input type="text" id="op" name="op" />
<input type="text" id="num2" name="num2" />
<br />
<input type="button" value="Solve" onClick="calc(this)">
<p id="result" name="r1">
<br />
</p>
</body>
</html>
I used the parseint() because your expressions in your if statements were treating values like text.
Next we need to use === Three equals which says A is really equal to + or what ever the second input value is.
Third was the onclick, I did a (this) and feed back form as you can see in the line that says function calc.
For good measure I added a return false; to prevent form submission (but it will function without it).
Also like other posters stated it is else if and not elseif.
I hope this is helpful. Again, I would do things differently but got it working with some explanations.

I recommend using eval()
If the user inputs "5+6" or "(9*3)/5" and you set that to a variable, eval() will parse and solve the problem!

It's else if not elseif. Also you need to use parseInt on A+C, otherwise it will treat your strings as...well, strings. You should have seen the elseif error in your browser. Are you using something like firebug? If you aren't, start. Let tools do the hard work for you.

There is a way you can do it with a single input box:
function findOps(s) {
for (var i = 0; i < s.length; i++) {
if (s[i] == "+")
return "+";
if (s[i] == "-")
return "-";
if (s[i] == "*")
return "*";
if (s[i] == "/")
return "/";
}
}
var input = '';
function calc() {
var dom = $("#input");
input = dom.val();
try {
switch (findOps(input)) {
case "+":
var a = input.split("+");
var x = parseFloat(a[0]);
var y = parseFloat(a[1]);
var res = x + y;
if (!isNaN(res)) {
setTimeout(function() {
dom.val(res.toFixed(3));
dom.get(0).setSelectionRange(0, 0);
}, 150);
}
break;
case "-":
var a = input.split("-");
var x = parseFloat(a[0]);
var y = parseFloat(a[1]);
var res = x - y;
if (!isNaN(res)) {
setTimeout(function() {
dom.val(res.toFixed(3));
dom.get(0).setSelectionRange(0, 0);
}, 150);
}
break;
case "*":
var a = input.split("*");
var x = parseFloat(a[0]);
var y = parseFloat(a[1]);
var res = x * y;
if (!isNaN(res)) {
setTimeout(function() {
dom.val(res.toFixed(3));
dom.get(0).setSelectionRange(0, 0);
}, 150);
}
break;
case "/":
var a = input.split("/");
var x = parseFloat(a[0]);
var y = parseFloat(a[1]);
var res = x / y;
if (!isNaN(res)) {
setTimeout(function() {
dom.val(res.toFixed(3));
dom.get(0).setSelectionRange(0, 0);
}, 150);
}
break;
}
} catch (err) {
alert("catched¡");
}
}

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Amanpreet singh</title>
</head>
<body>
<center>
<table cellpadding="10" cellspacing="10" style="font-size:2em">
<tr><td>Number 1:</td>
<td><input type="text" id="num1" name="num1" /></td>
</tr>
<tr><td>Number 2:</td>
<td> <input type="text" id="num2" name="num2" /></td>
</tr>
<tr>
<td> <label for=" Operator"> Operator:</label></td>
<td> <select name="Operator" id="op" name="op">
<option value="+">Add</option> <option value="-">Subtract</option>
<option value="*">Muliply</option><option value="/">Divide</option>
</select></td>
</tr>
<tr><td colspan="2" align="cover">
<center> <input type="button" value="Solve" onclick="calc()" />
</center></td>
</tr>
<tr><td colspan="2" style="text-align: center;"><p id="result" name="r1" ></p></td></tr>
</table></center>
<script type="text/javascript">
function calc() {
var D = "0";
var A = document.getElementById("num1").value;
var B = document.getElementById("op").value;
var C = document.getElementById("num2").value;
if (B === "+")
{
D = parseInt(A)+parseInt(C);
}
else if(B === "-")
{
D = parseInt(A)-parseInt(C);
}
else if(B === "*")
{
D = parseInt(A)*parseInt(C);
}
else if (B === "/")
{
D = parseInt(A)/parseInt(C);
}
document.getElementById("result").innerHTML = "Result is :"+D;
return false;
}
</script>
</body>
</html>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Amanpreet singh</title>
</head>
<body>
<center>
<table cellpadding="10" cellspacing="10" style="font-size:2em">
<tr><td>Number 1:</td>
<td><input type="text" id="num1" name="num1" /></td>
</tr>
<tr><td>Number 2:</td>
<td> <input type="text" id="num2" name="num2" /></td>
</tr>
<tr>
<td> <label for=" Operator"> Operator:</label></td>
<td> <select name="Operator" id="op" name="op">
<option value="+">Add</option> <option value="-">Subtract</option>
<option value="*">Muliply</option><option value="/">Divide</option>
</select></td>
</tr>
<tr><td colspan="2" align="cover">
<center> <input type="button" value="Solve" onclick="calc()" />
</center></td>
</tr>
<tr><td colspan="2" style="text-align: center;"><p id="result" name="r1" ></p></td></tr>
</table></center>
<script type="text/javascript">
function calc() {
var D = "0";
var A = document.getElementById("num1").value;
var B = document.getElementById("op").value;
var C = document.getElementById("num2").value;
if (B === "+")
{
D = parseInt(A)+parseInt(C);
}
else if(B === "-")
{
D = parseInt(A)-parseInt(C);
}
else if(B === "*")
{
D = parseInt(A)*parseInt(C);
}
else if (B === "/")
{
D = parseInt(A)/parseInt(C);
}
document.getElementById("result").innerHTML = "Result is :"+D;
return false;
}
</script>
</body>
</html>

Related

Should I be using else-if statements for these?

I'm very new to coding, and have been trying to create a very simple calculator using HTML and JavaScript where the user inputs two values, selects an operator from a selection of buttons, and then gets a result.
I'd appreciate some guidance from people who know what they're doing!!
I've tried implementing else-ifs, but it doesn't appear to be solving the issue. Only the last line of the function is executing. Python wasn't this hard?!
<button id="a" value="+">+</button>
<button id="b" value="-">-</button>
<button id="c" value="/">/</button>
<button id="d" value="X">X</button>
<input type="text" id="n1"/>
<input type="text" id="n2"/>
<script>
function calc()
{
var n1 = parseFloat(document.getElementById('n1').value);
var n2 = parseFloat(document.getElementById('n2').value);
var a = document.getElementById("a").value;
var b = document.getElementById("b").value;
var c = document.getElementById("c").value;
var d = document.getElementById("d").value;
if(a === '+')
{
document.getElementById('result').value = n1+n2;
}
if(b === '-')
{
document.getElementById('result').value = n1-n2;
}
if(c === '/')
{
document.getElementById('result').value = n1/n2;
}
if(d === 'X')
{
document.getElementById('result').value = n1*n2;
}
}
</script>
I'm expecting each line to be executed to produce the correct operand, but at present the only last line (n1*n2) is giving me anything.
All your conditions are true, since the value of a button doesn't change depending on whether the user clicked on it.
You should change calc() so it takes the button as a parameter, then checks the value of the parameter's value. A switch statement is an easy way to write this type of check.
function calc(button) {
var n1 = parseFloat(document.getElementById('n1').value);
var n2 = parseFloat(document.getElementById('n2').value);
let result;
switch (button.value) {
case '+':
result = n1 + n2;
break;
case '-':
result = n1 - n2;
break;
case '/':
result = n1 / n2;
break;
case 'X':
result = n1 * n2;
break;
}
document.getElementById('result').value = result;
}
<input type="text" id="n1" />
<input type="text" id="n2" /><br>
<button id="a" value="+" onclick="calc(this)">+</button>
<button id="b" value="-" onclick="calc(this)">-</button>
<button id="c" value="/" onclick="calc(this)">/</button>
<button id="d" value="X" onclick="calc(this)">X</button>
<br>
<input type="text" id="result" readonly />

Deactivate a button until all javascript conditions have been checked

I´m trying to do different javascript validations before sending a form, the problem is that I haven´t been able to prevent the form from submit, it checks the conditions and sends alerts when a conditions hasn´t been satisfied but it sends the form anyways. I want the button to either be disabled until everything is right or send a message telling user, to check the cuenta.
Thanks in advance. This is my code:
<form action="<?php echo base_url();?>index.php/Datos/agregar" method="post">
Enter CLABE account:
<input name="clabe" id="clabe" type = "text" pattern=".{17,17}" maxlength="17" required title="17 números exactamente"/>
<input type="text" name="control" id="control" maxlength="1" size="2" required >
Again:
<input name="clabe2" id="clabe2" type = "text" pattern=".{17,17}" maxlength="17" required title="17 números exactamente"/>
<input type="text" name="control2" id="control2" maxlength="1" size="2" required>
<hr>
Bank: <input type="text" name="Banco" id="Banco" readonly required onmousemove="comparaclabe();" >
<hr>
Observations: <input type="text" name="Observaciones" id="Observaciones" required>
<hr>
<input type="submit" id="myBtn" value="Guardar Cambios" onclick ="return compareclabe();" ><span id="msg"></span>
<hr>
<input type="hidden" id="cve_banco" name="cve_banco">
</form>
<hr>
<script>
function compareclabe(){
document.getElementById("myBtn").disabled = true;
var x1 = document.getElementById("clabe").value;
var x2 = document.getElementById("control").value;
var x3 = x1 + x2;
var z1 = document.getElementById("clabe2").value;
var z2 = document.getElementById("control2").value;
var z3 = z1 + z2;
if( x3 != z3){
alert("keys are not equal");
return false;
}else if (x3 == z3){
this.someFunc(); //I want to call function someFunc and then
if the result is true, execute the next code
if (true){
var cBanco = String(x3).charAt(0) + String(x3).charAt(1) + String(x3).charAt(2);
var x = cBanco;
switch (x) {
case "012":
text = "BBVA BANCOMER";
break;
case "014":
text = "SANTANDER";
break;
case "032":
text = "IXE";
break;
default:
text = "No value found";
}
document.getElementById("Banco").value = text;
document.getElementById("myBtn").disabled = false;
return true;
}
}else{
return false;
}
}
function someFunc() {
//myFunction2();
var x = document.getElementById("clabe2").value;
f2(x,'37137137137137137');
//return true;
}
function f2(a, b) {
var cad = Array.from(a, (v, i) => v * b[i] % 10).join('');
//se suman todos los digitos del array
var value = cad,
sum = value
.toString()
.split('')
.map(Number)
.reduce(function (a, b) {
return a + b;
}, 0);
//separate last digit from result
var number = sum;
// convert number to a string, then extract the first digit
var one = String(number).charAt(1);
// convert the first digit back to an integer
var one_as_number = Number(one);
var digito_control = (10 - one_as_number);
if (digito_control === 10 ) {
digito_control = 0;
var dg = digito_control;
}else{
dg = digito_control;
}
var z = document.getElementById("control2").value;
if (dg != z){
alert("checkig digit is not equal");
return false;
}
else if (dg == z){
alert("checkig digit is equal");
return true;
}
}
</script>
I changed form submit button type to "button" and if all the validations are passed, then submit form from javascript. See below code
function compareclabe() {
document.getElementById("myBtn").disabled = true;
var x1 = document.getElementById("clabe").value;
var x2 = document.getElementById("control").value;
var x3 = x1 + x2;
var z1 = document.getElementById("clabe2").value;
var z2 = document.getElementById("control2").value;
var z3 = z1 + z2;
if (x3 != z3) {
alert("keys are not equal");
return false;
} else if (x3 == z3) {
this.someFunc(); //I want to call function someFunc and then if the result is true, execute the next code
if (true) {
var cBanco = String(x3).charAt(0) + String(x3).charAt(1) + String(x3).charAt(2);
var x = cBanco;
switch (x) {
case "012":
text = "BBVA BANCOMER";
break;
case "014":
text = "SANTANDER";
break;
case "032":
text = "IXE";
break;
default:
text = "No value found";
}
document.getElementById("Banco").value = text;
document.getElementById("myBtn").disabled = false;
$('#form').submit(); //submit form if all validation succeeds
}
} else {
return false;
}
}
function someFunc() {
//myFunction2();
var x = document.getElementById("clabe2").value;
f2(x, '37137137137137137');
//return true;
}
function f2(a, b) {
var cad = Array.from(a, (v, i) => v * b[i] % 10).join('');
//se suman todos los digitos del array
var value = cad,
sum = value
.toString()
.split('')
.map(Number)
.reduce(function(a, b) {
return a + b;
}, 0);
//separate last digit from result
var number = sum;
// convert number to a string, then extract the first digit
var one = String(number).charAt(1);
// convert the first digit back to an integer
var one_as_number = Number(one);
var digito_control = (10 - one_as_number);
if (digito_control === 10) {
digito_control = 0;
var dg = digito_control;
} else {
dg = digito_control;
}
var z = document.getElementById("control2").value;
if (dg != z) {
alert("checkig digit is not equal");
return false;
} else if (dg == z) {
alert("checkig digit is equal");
return true;
}
}
<form action="<?php echo base_url();?>index.php/Datos/agregar" method="post" id="form"> <!-- I included an id to form -->
Enter CLABE account:
<input name="clabe" id="clabe" type="text" pattern=".{17,17}" maxlength="17" required title="17 números exactamente" />
<input type="text" name="control" id="control" maxlength="1" size="2" required> Again:
<input name="clabe2" id="clabe2" type="text" pattern=".{17,17}" maxlength="17" required title="17 números exactamente" />
<input type="text" name="control2" id="control2" maxlength="1" size="2" required>
<hr> Bank: <input type="text" name="Banco" id="Banco" readonly required onmousemove="comparaclabe();">
<hr> Observations: <input type="text" name="Observaciones" id="Observaciones" required>
<hr>
<input type="button" id="myBtn" value="Guardar Cambios" onclick="return compareclabe();"><span id="msg"></span>
<hr>
<input type="hidden" id="cve_banco" name="cve_banco">
</form>
<hr>
But there are many validation plugins where you can easily implement. No need to code from begining. Refer this for an example -> https://jqueryvalidation.org/
You can disable the button by default, and add event listeners to all the inputs in your form. But be weary of other ways to submit the form, like the enter key. I would add an onsubmit function just to prevent all ways the event can happen when you don't want it to.
const form = document.querySelector('form')
const inputs = [...form.querySelectorAll('input')] // convert node list to array
const isValid = () => {
let valid = false
disableButton()
// handle your conditions here
if (valid) enableButton()
return valid;
}
inputs.forEach( input => input.addEventListener('input', isValid))
form.onsubmit = event => if (!isValid()) event.preventDefault()
Or ES5 if you prefer:
var form = document.querySelector('form');
var inputNodes = form.querySelectorAll('input');
var inputs = Array.prototype.call.slice(inputNodes); // convert node list to array
var isValid = function() {
var valid = false;
disableButton();
// handle your conditions here
if (valid) enableButton();
return valid
}
inputs.forEach( function(input) {
input.addEventListener('input', isValid);
});
form.onsubmit = function(event) {
if (!isValid()) event.preventDefault();
};
It's also worth noting that HTML5 has a lot of built-in validation you can take advantage of.

Get Value From Disabled Textfield Javascript

function pretest() {
var a = document.getElementById('pre').value;
var result = parseInt(a);
if (a <= 50) {
document.getElementById('val').value = 1;
}else if(50<a && a<= 80){
document.getElementById('val').value = 2;
}else{
document.getElementById('val').value = 3;
}
}
function posttest(){
var a = document.getElementById('post').value;
var result = parseInt(a);
if (a <= 50) {
document.getElementById('val1').value = 1;
}else if(50<a && a<= 80){
document.getElementById('val1').value = 2;
}else{
document.getElementById('val1').value = 3;
}
}
function all(){
var a = document.getElementById('val').value;
var b = document.getElementById('val1').value;
var c = parseInt(a) + parseInt(b);
if (!isNaN(c)) {
document.getElementById('total').value = c;
}
}
<input onkeyup="pretest();" type="text" id="pre" name="pretest">
<input onkeyup="all();" type="text" id="val" name="val" disabled="disabled">
<input onkeyup="posttest();" type="text" id="post" name="posttest">
<input onkeyup="all();" type="text" id="val1" name="val1" disabled="disabled">
<input onkeyup="total();" type="text" id="total" name="total" disabled="disabled">
i have 5 text field
A1 A2(value onkeyup from A1 and disabled is true)
B1 B2(value onkeyup from B1 and disabled is true)
C(A2+B2 and disabled textfield)
How to get value for C textfield ? i used onkeyup, but didn't work
There are several things amiss in your code.
never, ever use parseInt(foo) without the radix-argument, especially when foo is arbitrary input. parseInt will otherwise take input 012 and think it's an octal value you gave it. Thus, make that parseInt(a, 10) to get a decimal, or use Number(a)
onkeyup won't fire on a disabled element - how could it? Nobody will be able to press a key there, since it's disabled. What you probably want is onchange, however...
...onchange (or oninput, which is a little more trigger-happy and what I've used below) won't fire when you manually set an element's value; it doesn't in vanilla JS, nor when using jQuery's val() - you have to trigger it manually
your code example is rushed, incomplete and I had to work considerably longer and harder to understand what you want than should be necessary; regardless...
/*
Especially with function names like `all` and `total`, you will want
to make sure to set up some sort of namespacing, e.g. using the
Revealing Module Pattern or other. These functions are attached to
the global window object and can be overriden by anything and anybody,
causing at least hard-to-trace bugs, maybe worse
*/
function pretest() {
var a = document.getElementById('pre').value;
var result = parseInt(a, 10);
if (a <= 50) {
document.getElementById('val').value = 1;
} else if (50 < a && a <= 80) {
document.getElementById('val').value = 2;
} else {
document.getElementById('val').value = 3;
}
// you have to explicitly call all() here, as the input-event
// won't be fired when manually setting value
all();
}
function posttest() {
var a = document.getElementById('post').value;
var result = parseInt(a, 10);
if (a <= 50) {
document.getElementById('val1').value = 1;
} else if (50 < a && a <= 80) {
document.getElementById('val1').value = 2;
} else {
document.getElementById('val1').value = 3;
}
all()
}
function all() {
var a = document.getElementById('val').value;
var b = document.getElementById('val1').value;
var c = parseInt(a, 10) + parseInt(b, 10);
if (!isNaN(c)) {
document.getElementById('total').value = c;
}
total();
}
total = function() {
//TODO implement
}
document.getElementById('pre').addEventListener('input', window.pretest);
document.getElementById('post').addEventListener('input', window.posttest);
<label for="pre">PRE</label><br>
<input type="text" id="pre" name="pretest">
<br><br>
<label for="val">val</label><br>
<input type="text" id="val" name="val" disabled="disabled">
<br><br>
<label for="post">POST</label><br>
<input type="text" id="post" name="posttest">
<br><br>
<label for="val1">val1</label><br>
<input type="text" id="val1" name="val1" disabled="disabled">
<br><br>
<label for="total">TOTAL</label><br>
<input type="text" id="total" name="total" disabled="disabled">
You can get value as from normal text input
function myFunction(){
document.getElementById("textPlace").disabled = true;
console.log(document.getElementById("textPlace").value)
}
<input type="text" onkeyup="myFunction()" id="textPlace">

GPA Calculator, how to make letter inputs into numbers

I am trying to make a simple GPA calculator. There are 4 forms and I'm trying to make it so a user enters 4 letters (A,B,C,D, or F) and have each of those numbers represent a value (A = 4.0, B=3.0 ect.) And basically just get the average of them all. Right now I just made it so it so it works if the user enters numbers, but now I want to change it so the user enters the letter grades and get the same gpa number. I have no idea how to do this. Please help thank you.
(This is my html)
<!DOCTYPE html>
<html>
<head>
<title>GPA Calculator</title>
<link type="text/css" rel="stylesheet" href="project6.css">
<script type="text/javascript" src="project6.js"></script>
</head>
<body>
<h1>Enter Your Grades Below</h1>
<form name="form" id="form">
<br>
<input type="text" class="textForm1" name="textForm1"></input><br>
<input type="text" class="textForm1" name="textForm2"></input><br>
<input type="text" class="textForm1" name="textForm3"></input><br>
<input type="text" class="textForm1" name="textForm4"></input><br>
<button type="button" onClick="getGrade()">Submit</button>
</form>
<div id="div">
</div>
</body>
</html>
(This is my javascript)
var getGrade = function() {
var inputOne = document.form.textForm1.value;
var inputTwo = document.form.textForm2.value;
var inputThree = document.form.textForm3.value;
var inputFour = document.form.textForm4.value;
document.getElementById("div").innerHTML = (Number(inputOne) + Number(inputTwo) + Number(inputThree) + Number(inputFour))/4;
}
The basic idea is you want to create a mapping between letters and numbers.
The simplest possible way to do this would be a series of if statements.
var input = document.querySelector('input');
input.addEventListener('input', function() {
var inputValue = input.value;
if (inputValue === 'A') {
inputValue = 4.0;
} else if (inputValue === 'B') {
inputValue = 3.0;
} else if (inputValue === 'C') {
inputValue = 2.0;
} else if (inputValue === 'D') {
inputValue = 1.0;
} else {
inputValue = 0.0;
}
console.log(inputValue);
});
1: <input type="text" />
but this gets very tedious, especially if you have multiple inputs. Another option would be to move this functionality into a function then use that function multiple times.
function letterToNumber(letter) {
if (letter === 'A') {
return 4.0;
} else if (letter === 'B') {
return 3.0;
} else if (letter === 'C') {
return 2.0;
} else if (letter === 'D') {
return 1.0;
} else {
return 0.0;
}
}
document.querySelector('button').addEventListener('click', function() {
var input1 = document.getElementById('input1').value;
var input2 = document.getElementById('input2').value;
var input3 = document.getElementById('input3').value;
var input4 = document.getElementById('input4').value;
input1 = letterToNumber(input1);
input2 = letterToNumber(input2);
input3 = letterToNumber(input3);
input4 = letterToNumber(input4);
console.log(input1, input2, input3, input4);
});
1: <input id="input1" type="text" /><br />
2: <input id="input2" type="text" /><br />
3: <input id="input3" type="text" /><br />
4: <input id="input4" type="text" /><br />
<button>Calculate</button>
This works fine. You could simplify it even further by creating an object where the keys match the letter and the value matches the actual number value.
var letterToNumber = {
A: 4.0,
B: 3.0,
C: 2.0,
D: 1.0
};
document.querySelector('button').addEventListener('click', function() {
var input1 = document.getElementById('input1').value;
var input2 = document.getElementById('input2').value;
var input3 = document.getElementById('input3').value;
var input4 = document.getElementById('input4').value;
input1 = letterToNumber[input1];
input2 = letterToNumber[input2];
input3 = letterToNumber[input3];
input4 = letterToNumber[input4];
console.log(input1, input2, input3, input4);
});
1: <input id="input1" type="text" /><br />
2: <input id="input2" type="text" /><br />
3: <input id="input3" type="text" /><br />
4: <input id="input4" type="text" /><br />
<button>Calculate</button>
No matter what approach you take, remember the basic principle: if I get some value X I want to get some value Y. These are just examples of how to map that idea.
There's also a JavaScript Map that will handle all the association for you.
MDN JavaScript Reference: Map
var vals = new Map();
vals.set("A", 4.0);
vals.set("B", 3.0);
vals.set("C", 2.0);
vals.set("D", 1.0);
vals.set("F", 0.0);
And to retrieve:
var grade = document.getElementById("myGrade");
var gradeVal = vals.get(grade);
Of course you would do the retrieval in a loop, getting the values for all the grades entered by a user and calculating the average. This is just a simple example of using a Map.
I would create another Javascript function that takes the input and calculates it, and then you can output from that function.
Inside the function, you can change the letters to numbers.
JavaScript
const calculateGrade = () => {
const grades = [inputOne, inputTwo, inputThree, inputFour]
let sum = 0
for (let i = 0; i < grades.length; i++) {
switch (grades[i]) {
case "A":
sum += 4.0
case "B":
sum += 3.0
case "C":
sum += 2.0
case "D":
sum += 1.0
}
}
return (sum / 4)
}
I read all the answers and all gave me different ideas of what to do, but in the end, I followed mostly what Mike C. did, but not exactly the same way. Here's what I ended up with that worked perfectly.
var gradeValues = {
"A": 4.0,
"B": 3.0,
"C": 2.0,
"D": 1.0,
"F": 0
};
var getGrade = function() {
input1 = document.form.input1.value;
input2 = document.form.input2.value;
input3 = document.form.input3.value;
input4 = document.form.input4.value;
document.getElementById("result").innerHTML = ((gradeValues[input1] + gradeValues[input2] + gradeValues[input3] + gradeValues[input4]) / 4) + " is your GPA";
};

How to get an input value dynamically and perform arithmetic operations using javascript

I have created two input text fields by which the user have to give two values. Using javascript, I need to get those values perform addition, subtraction, multiplication and division based on the checkbox checked. How to do that?
Here is my code..
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>JS Assignment</title>
<script>
function changeCheckBox() {
try {
var max = document.myform.check.length;
var count = 0;
for (var i = 0; i < max; i++) {
if (document.myform.check[i].checked == true) {
count++;
serNoChecked = i;
}
}
if (count == 1) {
for (var i = 0; i < max; i++) {
if (document.myform.check[i].checked == false) {
document.myform.check[i].disabled = true;
}
}
} else if (count == 0) {
for (var i = 0; i < max; i++) {
document.myform.check[i].disabled = false;
}
}
if (null == max) return false;
if (count == 0) {
return true;
} else if (count > 0) {
return false;
}
} catch (e) {
alert(e.message);
}
}
</script>
<script type="text/javascript">
function arith()
{
var number1 = document.getElementById('num1').value;
var number2 = document.getElementById('num2').value;
x=num1 + num2;
var demoP=document.getElementById("demo")
demoP.innerHTML="x=" + x;
}
</script>
</head>
<body background="photo.jpg" onload="arith()">
<h3>Simple JavaScript Arithmetic Operations</h3>
<form name="myform" method="get">
Value 1 <input type ="text" id="num1"> <br><br>
Value 2 <input type="text" id="num2"> <br><br>
<input type="checkbox" name="check" value="check1" id="check1" onclick="changeCheckBox()">Addition<br>
<input type="checkbox" name="check" value="check2" id="check2" onclick="changeCheckBox()">Subtraction<br>
<input type="checkbox" name="check" value="check3" id="check3" onclick="changeCheckBox()">Multiplication<br>
<input type="checkbox" name="check" value="check4" id="check4" onclick="changeCheckBox()">Division<br><br>
<input type="submit" value="Submit">
</form>
<p id="demo"></p>
</body>
</html>
Try sending the value of the HTML into the function, and then use those as an if statement check (or switch statement).
<form name="myform" method="get">
Value 1 <input type ="text" id="num1"> <br><br>
Value 2 <input type="text" id="num2"> <br><br>
<input type="checkbox" name="check" id="check1">Addition<br>
<input type="checkbox" name="check" id="check2">Subtraction<br>
<input type="checkbox" name="check" id="check3">Multiplication <br>
<input type="checkbox" name="check" id="check4">Division<br><br>
<input type="submit" value="Submit">
<p id="demo"></p>
Notice the value attributes now have unique value. And you're sending that into the function as a parameter.
Now just have a function that returns what you want
var newVal = "Unset";
var plus = document.getElementById("check1");
var minus = document.getElementById("check2");
var times = document.getElementById("check3");
var divide = document.getElementById("check4");
var demoP=document.getElementById("demo");
plus.onclick = function() {
var n1 = parseFloat(document.getElementById('num1').value);
var n2 = parseFloat(document.getElementById('num2').value);
newVal = n1+n2;
demoP.innerHTML="x=" + newVal;
}
minus.onclick = function() {
var n1 = parseFloat(document.getElementById('num1').value);
var n2 = parseFloat(document.getElementById('num2').value);
newVal = n1-n2;
demoP.innerHTML="x=" + newVal;
}
times.onclick = function() {
var n1 = parseFloat(document.getElementById('num1').value);
var n2 = parseFloat(document.getElementById('num2').value);
newVal = n1*n2;
demoP.innerHTML="x=" + newVal;
}
divide.onclick = function() {
var n1 = parseFloat(document.getElementById('num1').value);
var n2 = parseFloat(document.getElementById('num2').value);
newVal = n1/n2;
demoP.innerHTML="x=" + newVal;
}

Categories

Resources