Using radio buttons for a calculator - javascript

I am trying to make a simple calculator using radio buttons to select addition, subtraction, multiplication or division. However it is not working. I have tried a lot of things and googled it a lot, but I can't find out the issue. If anyone finds a problem with what I have, could you please give me a solution. Thanks!
<html>
<head>
<script language="javascript">
function operation() {
var ans =document.getElementById("answer").value;
if (document.getElementById("add").value = "add") {
ans= calculate(add);
}
if (document.getElementById("subtract").value = "subtract") {
ans= calculate(subtract);
}
if (document.getElementById("multiply").value = "multiply") {
ans= calculate(multiply);
}
if (document.getElementById("divide").value = "divide") {
ans= calculate(divide);
}
}
function calculate(action){
var num1 = document.getElementById("num1").value;
var num2 = document.getElementById("num2").value;
var result;
switch(action){
case add:
result= parseInt(num1)+parseInt(num2);
break;
case subtract:
result= num1-num2;
break;
case multiply:
result= num1*num2;
break;
case divide:
result= num1/num2;
break;
}
return result;
</script>
<title>
Calculator
</title>
</head>
<body>
<form>
<input type="text" id="num1">
+<input type="radio" name="group1" id="add" value="add">
-<input type="radio" name="group1" id="subtract" value="subtract">
*<input type="radio" name="group1" id="multiply" value="multiply">
/<input type="radio" name="group1" id="divide" value="divide">
<input type="text" id="num2">
=
<input type="text" id="answer" readonly>
<input type="button" value="Calculate" onClick="calculate()">
</form>
</body>
</html>

Your calculate function takes an argument:
function calculate(action){}
You are calling it without passing any paremeters:
<input type="button" value="Calculate" onClick="calculate()">
actually, i made this FIDDLE as the answer for someone's question few days ago. Is this some sort of homework?
function operation() {
var ans =document.getElementById("answer");
if (document.getElementById("add").checked) {
ans.value= calculate('add');
}
if (document.getElementById("subtract").checked) {
ans.value= calculate('subtract');
}
if (document.getElementById("multiply").checked) {
ans.value= calculate('multiply');
}
if (document.getElementById("divide").checked) {
ans.value= calculate('divide');
}
}
function calculate(action){
var num1 = document.getElementById("num1").value;
var num2 = document.getElementById("num2").value;
var result;
switch(action){
case 'add':
result= parseInt(num1)+parseInt(num2);
break;
case 'subtract':
result= num1-num2;
break;
case 'multiply':
result= num1*num2;
break;
case 'divide':
result= num1/num2;
break;
}
return result;
}
fiddle

You're not putting the result back into the answer box. You can return the value, but you have to tell it what text element to use.
document.getElementById("answer").value = ans;
In your if statements... "=" means assignment. "==" is comparison.
You have set the "value" of each radio button to something. So, you're checking if the value for "add" is "add", but you have already explicitly set the value to "add". Radio buttons are boolean: true or false.
function op() {
var ans = 0;
if (document.getElementById("add").value) {
ans= calculate(add);
} else if (document.getElementById("subtract").value) {
ans= calculate(subtract);
} else if (document.getElementById("multiply").value) {
ans= calculate(multiply);
} else if (document.getElementById("divide").value) {
ans= calculate(divide);
}
document.getElementById("answer").value = ans;
}
function calculate(action){
var num1 = document.getElementById("num1").value;
var num2 = document.getElementById("num2").value;
var result;
switch(action){
case add:
result= parseInt(num1)+parseInt(num2);
break;
case subtract:
result= num1-num2;
break;
case multiply:
result= num1*num2;
break;
case divide:
result= num1/num2;
break;
}
return result;
}
<input type="button" value="Calculate" id="b" onclick="op();">

You are looking at the values of buttons to see if they are active. They will always have the value that is assigned to them whether they are checked or not.
if (document.getElementById("add").value = "add") {
...when you should be checking to see if they're checked.
if (document.getElementById("add").getAttribute("checked") == "checked") {
Also, in JavaScript "==" is used for comparison, "=" is used to assign a value.

Related

basic calculator created in javascript.. use an alert to tell user about any errors. the possible errors include:

I've created a basic 4 function calculator in JavaScript and now I need to use an alert to tell the user about any errors. the possible errors are:
One or both input fields are blank
One or both input fields < -9999 or greater than 9999
Divide by zero
Illegal character in either input field. Only 0, 1 ,2 ,3 ,4 ,5 ,6 ,7 ,8 ,9, and – are allowed.
Code:
function multiplyBy() {
num1 = document.getElementById("firstNumber").value;
num2 = document.getElementById("secondNumber").value;
document.getElementById("result").innerHTML = num1 * num2;
}
function divideBy() {
num1 = document.getElementById("firstNumber").value;
num2 = document.getElementById("secondNumber").value;
document.getElementById("result").innerHTML = num1 / num2;
}
function additionBy() {
num1 = parseInt(document.getElementById("firstNumber").value);
num2 = parseInt(document.getElementById("secondNumber").value);
document.getElementById("result").innerHTML = num1 + num2;
}
function subtractionBy() {
num1 = parseInt(document.getElementById("firstNumber").value);
num2 = parseInt(document.getElementById("secondNumber").value);
document.getElementById("result").innerHTML = num1 - num2;
}
body {
margin: 30px;
}
<!DOCTYPE html>
<html>
<head>
<body>
<form>
1st Number : <input type="text" id="firstNumber"> 2nd Number: <input type="text" id="secondNumber"> The Result is :
<span id="result"></span>
<br>
</br>
<br>
<input type="button" onClick="multiplyBy()" Value="Multiply" />
<input type="button" onClick="divideBy()" Value="Divide" />
<input type="button" onClick="additionBy()" Value="Add" />
<input type="button" onClick="subtractionBy()" Value="Sub" />
</br>
</form>
<script type="text/javascript" src="fourth.js">
</script>
</body>
</html>
first of all define the input tag type as number like below
1st Number : <input type="number" id="firstNumber" >
2nd Number: <input type="number" id="secondNumber" >
so, in that case user will not be able to enter invalid input.
secondly, check the divide by zero condition into the function only
There are libraries for validation that you can get but lets start simple. Rework what you have to remove duplicated code and then add functions to do your validation.
This is JUST A START not a complete solution, you have to do work. I will leave it to you to add the OTHER validation you need, but you can see how this is doing it with the couple I added.
function showResults(results) {
document.getElementById("result").innerHTML = results;
}
function multiplyBy(number1, number2) {
num1 = number1.value;
num2 = number2.value;
showResults(num1 * num2);
}
function divideBy(number1, number2) {
num1 = number1.value;
num2 = number2.value;
showResults(num1 / num2);
}
function additionBy(number1, number2) {
num1 = parseInt(number1.value, 10);
num2 = parseInt(number2.value, 10);
showResults(num1 + num2);
}
function subtractionBy(number1, number2) {
num1 = parseInt(number1.value, 10);
num2 = parseInt(number2.value, 10);
showResults(num1 - num2);
}
function actionClicker() {
let number1 = document.getElementById("firstNumber");
let number2 = document.getElementById("secondNumber");
validateNumber(number1);
validateNumber(number2);
var attribute = this.getAttribute("data-myattribute");
var expr = attribute;
switch (expr) {
case 'multiply':
multiplyBy(number1, number2);
break;
case 'division':
divideBy(number1, number2);
break;
case 'subtract':
subtractionBy(number1, number2);
break;
case 'addition':
additionBy(number1, number2);
break;
default:
console.log('Sorry, we do not find ' + expr + '.');
}
}
function showValidationMessage(message) {
alert(message);
}
function isNumeric(n) {
return !isNaN(parseFloat(n)) && isFinite(n);
}
function isEmpty(n) {
return n === "";
}
function isInRange(n) {
if (isNumeric(n) && !isEmpty(n)) {
num = parseInt(n, 10);
return num >= -9999 && num <= 9999;
}
return false;
}
function validateNumber(el) {
let hasError = false;
el.classList.remove("has-error");
// add your validation
let message = "get stuff better";
if (!isNumeric(el.value)) {
message = "Not a number.";
hasError = true;
}
if (isEmpty(el.value)) {
message = "Not a number, cannot be empty.";
hasError = true;
}
if (hasError) {
el.classList.add("has-error");
showValidationMessage(message);
}
}
function modifyNumbers(event) {
let el = event.target;
validateNumber(el);
}
var num1 = document.getElementById("firstNumber");
var num2 = document.getElementById("secondNumber");
var buttons = document.getElementsByClassName('actions');
// add event listener to buttons
for (var i = 0; i < buttons.length; i++) {
buttons[i].addEventListener('click', actionClicker, false);
}
num1.addEventListener("change", modifyNumbers, false);
num2.addEventListener("change", modifyNumbers, false);
body {
margin: 30px;
}
.buttons {
margin: 2em;
}
label {
padding-right: 1em;
padding-left: 1em
}
.has-error {
background-color: lightpink;
border: solid red 1px;
}
.numbers {
width: 11em;
}
<body>
<form>
<label for="firstNumber">1st Number:</label><input class="numbers" type="number" id="firstNumber" placeholder="Min: -9999, max: 9999" min="-9999" max="9999" /><span class="validity"></span><label for="secondNumber">2nd Number:</label><input class="numbers"
type="number" id="secondNumber" placeholder="Min: -9999, max: 9999" min="-9999" max="9999" /><span class="validity"></span>
<div><label>The Result is:</label>
<div id="result"></div>
</div>
<div class="buttons">
<button type="button" class="actions" id="multiply" data-myattribute="multiply">Multiply</button>
<button type="button" class="actions" id="divide" data-myattribute="division">Divide</button>
<button type="button" class="actions" id="add" data-myattribute="addition">Add</button>
<button type="button" class="actions" id="subtract" data-myattribute="subtract">Sub</button>
</div>
</form>
</body>
What you are looking for is a validation pattern.
To check if the inputs are valid you can perform checks at the beginning of your math functions. For example
var $num1 = document.getElementById("firstNumber");
var $num2 = document.getElementById("secondNumber");
var $result = document.getElementById("result");
function checkValid(division){
var num1 = $num1.value;
var num2 = $num2.value;
if(num1 == null || num1 > 9999 || num1 < -9999){
return false;
}
if(num2 == null || num2 > 9999 || num2 < -9999){
return false;
}
if(division && num2 === 0){
return false
}
}
function multiplyBy() {
if(check()){
num1 = $num1.value;
num2 = $num2.value;
$result.innerHTML = num1 * num2;
} else {
alert('some error message');
}
}
then in your division function call check(true)
This is just one way to handle it. You could call alert in the check function before returning or even return your error messages from the check function. This should get going in the right direction.
Also I do recommend the <input type="number"> changes by Hasan as well.

change() jQuery not working

I'm having some trouble getting my change() event working in jQuery. I am making a small program that converts temperatures to Kelvin, and I want the span that holds my value after conversion to update 1) every time the temperature to convert changes and 2) every time a different temperature scale is selected from the radio buttons.
Relevant Code:
$(document).ready(function() {
$('input[type=radio]').checkboxradio();
var temp = parseFloat()
$('input.listener').change(function() {
var name = $(this).attr("name");
var val = $(this).val();
switch (name) {
case 'unit':
var temperature = $('input#temp').val();
switch (val) {
case 'f':
$('span#output').html(((temperature - 32) / 1.8) + 273.15);
break;
case 'c':
$('span#output').html(temperature + 273.15);
break;
case 'r':
$('span#output').html(temperature / 1.8);
break;
}
case 'temp':
var u = $('input[name=unit]:checked').val();
switch (u) {
case 'f':
$('span#output').html(((val - 32) / 1.8) + 273.15);
break;
case 'c':
$('span#output').html(val + 273.15);
break;
case 'r':
$('span#output').html(val / 1.8);
break;
}
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="widget">
<fieldset>
<legend>Select a Unit to Convert to Kelvin: </legend>
<label for="fRadio">Fahrenheit</label>
<input id="fRadio" class="listener" type="radio" name="unit" value="f">
<label for="cRadio">Celsius</label>
<input id="cRadio" class="listener" type="radio" name="unit" value="c">
<label for="rRadio">Rankine</label>
<input id="rRadio" class="listener" type="radio" name="unit" value="r">
</fieldset>
</div>
<h2>Temperature Converter</h2>
<p>Type a value in the Fahrenheit field to convert the value to Kelvin:</p>
<p>
<label>Temperature</label>
<input id="temp" class="listener" type="number" value="32">
</p>
<p>Kelvin: <span id="output"></span></p>
My guess is I'm making a pretty dumb small mistake, but I can't seem to figure it out. Thanks for any and all help, suggestions, and solutions.
Two mistakes with your code:
Forgetting breaks; for the parent switch statement.
Forgetting name="temp" on the temperature field.
I changed the final temperature to a variable and made that the text of the output just so that there would be so many $('span#output').html(temperature);
Also, you should use the oninput event to detect a change for the number field.
$(document).ready(function() {
//$('input[type=radio]').checkboxradio();
var temp = parseFloat();
$('input.listener').on('change', updateTemp);
$('input.listener').on('input', updateTemp);
function updateTemp() {
var name = $(this).attr("name");
var val = $(this).val();
var final;
switch (name) {
case 'unit':
var temperature = $('input#temp').val();
switch (val) {
case 'f':
final = ((temperature - 32) / 1.8) + 273.15;
break;
case 'c':
final = temperature + 273.15;
break;
case 'r':
final = temperature / 1.8;
break;
}
break;
case 'temp':
var u = $('input[name=unit]:checked').val();
switch (u) {
case 'f':
final = ((val - 32) / 1.8) + 273.15;
break;
case 'c':
final = val + 273.15;
break;
case 'r':
final = val / 1.8;
break;
}
break;
}
$("#output").text(final);
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="widget">
<fieldset>
<legend>Select a Unit to Convert to Kelvin: </legend>
<label for="fRadio">Fahrenheit</label>
<input id="fRadio" class="listener" type="radio" name="unit" value="f">
<label for="cRadio">Celsius</label>
<input id="cRadio" class="listener" type="radio" name="unit" value="c">
<label for="rRadio">Rankine</label>
<input id="rRadio" class="listener" type="radio" name="unit" value="r">
</fieldset>
</div>
<h2>Temperature Converter</h2>
<p>Type a value in the Fahrenheit field to convert the value to Kelvin:</p>
<p>
<label>Temperature</label>
<input id="temp" class="listener" type="number" name="temp" value="32">
</p>
<p>Kelvin: <span id="output"></span></p>
You should set one of the radio buttons as default with checked="checked". Then try following:
$(document).ready(function () {
$('input.listener').change(function () {
if ($(this).attr("type") == 'radio') {
//radio button changed
var u = $(this).val();
} else {
var u = $("input[type='radio']:checked").val();
}
var temperature = $('#temp').val();
switch (u) {
case 'f':
$('span#output').html(((temperature - 32) / 1.8) + 273.15);
break;
case 'c':
$('span#output').html(temperature + 273.15);
break;
case 'r':
$('span#output').html(temperature / 1.8);
break;
}
});
});
You do not have break; after
case 'unit':
and when var name = "temp"
var val = $(this).val();
the value of var val above would be a number in string format, so when you do val + something in case 'temp' the number is getting appended instead getting added or substracted. Use parseInt(val) to convert the value of input box to integer in case of 'temp'.

ValueChange event in input

<input type='number' id='number1'/>
This is where I input numbers to later do operations on them (adding up etc). I've got that part covered up, but I wanted to extend this into deleting the total, which is stored in <span id='total'></span>, anytime something new is written in <input/>.
Firstly, I tried addEventListener('input', function());, but the thing is, it works even on input that's not registered. So, since I have <input type='number'/> if I write in 'abcd' etc. nothing changes, but the total is cleaned, because it triggers 'input' event listener. So I did some digging, and found ValueChange event listener, but I can't get it to work (but the value of input obviously changes).
Just to be honest, I checked for solutions, and are responses are either in regards to jQuery or some workarounds.
Code:
<!DOCTYPE html>
<html>
<head>
<meta charset='utf-8'/>
<title>Kalkulator-JS</title>
<script>
function operation(x) {
var typeOfOp = x;
var n1 = document.getElementById('number1').value;
var n2 = document.getElementById('number2').value;
var total = '';
console.log('Type of operation: ' + typeOfOp);
console.log('Number 1: ' + n1);
console.log('Number 2: ' + n2);
if (isNumber(n1)==false || isNumber(n2)==false) {
alert('Input right data');
return false;
}
n1 = Number(n1);
n2 = Number(n2);
switch (typeOfOp) {
case '+':
total = (n1 + n2);
break;
case '-':
total = (n1 - n2);
break;
case '*':
total = (n1 * n2);
break;
case '/':
if (n2 == 0) {
alert("You can't divide by 0!!!");
czysczenie();
return false;
}
total = (n1 / n2);
}
document.getElementById('total').innerHTML = total;
}
function isNumber(n) {
return !isNaN(parseFloat(n)) && isFinite(n);
}
function cleanup() {
document.getElementById('total').innerHTML = '';
}
document.addEventListener('DOMContentLoaded', function() {
var sum = document.getElementById('sum');
var subtract = document.getElementById('subtract');
var multiply = document.getElementById('multiply');
var divide = document.getElementById('divide');
sum.addEventListener('click', function() {
operation(sum.value);
});
subtract.addEventListener('click', function() {
operation(subtract.value);
});
multiply.addEventListener('click', function() {
operation(multiply.value);
});
divide.addEventListener('click', function() {
operation(divide.value);
});
document.getElementById('number1').addEventListener('input', function() {
cleanup();
});
});
</script>
</head>
<body>
<table>
<tr>
<td>Number 1</td>
<td>Number2</td>
</tr>
<tr>
<td><input type='number' id='number1'/></td>
<td><input type='number' id='number2'/></td>
</tr>
</table>
<input type='button' id='sum' value='+'/>
<input type='button' id='subtract' value='-'/>
<input type='button' id='multiply' value='*'/>
<input type='button' id='divide' value='/'/>
<div id='text'>
Total: <span id='total'></span>
</div>
</body>
</html>
If I understand correctly, I believe what you want is addEventListener('keydown', function()). Like so:
document.getElementById('liczba1').addEventListener('keydown', function(e) {
if(e.which >= 48 && e.which <= 57) //if 0-9 is pressed
czyszczenie();
});
Explanation:
When using Event Listeners an Event object is passed into the function giving you information about the event that has occurred. In this case the keydown event object has information about which the key has been pressed.
Full Code Example:
function dzialanie(x) {
var typDzialania = x;
var n1 = document.getElementById('liczba1').value;
var n2 = document.getElementById('liczba2').value;
var wynik = '';
console.log('Typ dzialania: ' + typDzialania);
console.log('Liczba 1: ' + n1);
console.log('Liczba 2: ' + n2);
if (isNumber(n1) == false || isNumber(n2) == false) {
alert('Wprowadź poprawne dane');
return false;
}
n1 = Number(n1);
n2 = Number(n2);
switch (typDzialania) {
case '+':
wynik = (n1 + n2);
break;
case '-':
wynik = (n1 - n2);
break;
case '*':
wynik = (n1 * n2);
break;
case '/':
if (n2 == 0) {
alert('Nie dziel przez 0!!!');
czysczenie();
return false;
}
wynik = (n1 / n2);
}
document.getElementById('wynik').innerHTML = wynik;
}
function isNumber(n) {
return !isNaN(parseFloat(n)) && isFinite(n);
}
function czyszczenie() {
document.getElementById('wynik').innerHTML = '';
}
document.addEventListener('DOMContentLoaded', function() {
var dodawanie = document.getElementById('dodawanie');
var odejmowanie = document.getElementById('odejmowanie');
var mnozenie = document.getElementById('mnozenie');
var dzielenie = document.getElementById('dzielenie');
dodawanie.addEventListener('click', function() {
dzialanie(dodawanie.value);
});
odejmowanie.addEventListener('click', function() {
dzialanie(odejmowanie.value);
});
mnozenie.addEventListener('click', function() {
dzialanie(mnozenie.value);
});
dzielenie.addEventListener('click', function() {
dzialanie(dzielenie.value);
});
document.getElementById('liczba1').addEventListener('keydown', function(e) {
if(e.which >= 48 && e.which <= 57) //if 0-9 is pressed
czyszczenie();
});
document.getElementById('liczba2').addEventListener('keydown', function(e) {
if(e.which >= 48 && e.which <= 57) //if 0-9 is pressed
czyszczenie();
});
});
<!DOCTYPE html>
<html>
<body>
<table>
<tr>
<td>Liczba 1</td>
<td>Liczba 2</td>
</tr>
<tr>
<td>
<input type='number' id='liczba1' />
</td>
<td>
<input type='number' id='liczba2' />
</td>
</tr>
</table>
<input type='button' id='dodawanie' value='+' />
<input type='button' id='odejmowanie' value='-' />
<input type='button' id='mnozenie' value='*' />
<input type='button' id='dzielenie' value='/' />
<div id='tekst'>
Wynik: <span id='wynik'></span>
</div>
</body>
</html>
SOLUTION, thanks to discussion between #Teemu and #imtheman, thanks a lot guys!
<!DOCTYPE html>
<html>
<head>
<meta charset='utf-8'/>
<title>Kalkulator-JS</title>
<script>
function operation(x) {
var typeOfOp = x;
var n1 = document.getElementById('number1').value;
var n2 = document.getElementById('number2').value;
var total = '';
console.log('Type of operation: ' + typeOfOp);
console.log('Number 1: ' + n1);
console.log('Number 2: ' + n2);
if (isNumber(n1)==false || isNumber(n2)==false) {
alert('Input right data');
return false;
}
n1 = Number(n1);
n2 = Number(n2);
switch (typeOfOp) {
case '+':
total = (n1 + n2);
break;
case '-':
total = (n1 - n2);
break;
case '*':
total = (n1 * n2);
break;
case '/':
if (n2 == 0) {
alert("You can't divide by 0!!!");
czysczenie();
return false;
}
total = (n1 / n2);
}
document.getElementById('total').innerHTML = total;
}
function isNumber(n) {
return !isNaN(parseFloat(n)) && isFinite(n);
}
function cleanup() {
document.getElementById('total').innerHTML = '';
}
document.addEventListener('DOMContentLoaded', function() {
var sum = document.getElementById('sum');
var subtract = document.getElementById('subtract');
var multiply = document.getElementById('multiply');
var divide = document.getElementById('divide');
sum.addEventListener('click', function() {
operation(sum.value);
});
subtract.addEventListener('click', function() {
operation(subtract.value);
});
multiply.addEventListener('click', function() {
operation(multiply.value);
});
divide.addEventListener('click', function() {
operation(divide.value);
});
document.getElementById('number1').addEventListener('keydown', function(e) {
if (isNumber(e.key)) {
cleanup();
}
});
});
</script>
</head>
<body>
<table>
<tr>
<td>Number 1</td>
<td>Number2</td>
</tr>
<tr>
<td><input type='number' id='number1'/></td>
<td><input type='number' id='number2'/></td>
</tr>
</table>
<input type='button' id='sum' value='+'/>
<input type='button' id='subtract' value='-'/>
<input type='button' id='multiply' value='*'/>
<input type='button' id='divide' value='/'/>
<div id='text'>
Total: <span id='total'></span>
</div>
</body>
</html>
Explanation:
My first bite into it, ValueChange is useless, because it's XUL (dunno what it is yet, but it's useless), gotta use something DOM-related
I have to use one of the event listeners I've tried before (keydown/input), but filter the result
I am bad with using objects, and the keydown event object is much easier to understand than input one (much simplier)
e.key (or event.key) gives me the value of key property of event
So now we need to validate if key pressed is a number or not.
But we can't use inbuilt function of Number(), because empty slots, like Number(' '), equal 0
So I make my own function, isNumber. And voilà.

Result is not showing

<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
var result = document.getElementById('answer').value;
if (document.getElementById('add')) {
function myFunction() {
add1 = document.getElementById('num1').value;
add2 = document.getElementById('num2').value;
ans = (parseInt(add1)+parseInt(add2));
result.innerHTML = ans;
}
}
</script>
</head>
<body>
<input type="text" id="num1" />
<select id="problem">
<option id="add">+</option>
<option id="sub">-</option>
<option id="mul">x</option>
<option id="div">÷</option>
</select>
<input type="text" id="num2" />
<br />
<input type="submit" onclick="myFunction();" />
<br />
<input type="text" id="answer" readonly />
</body>
</html>
I'm trying to make a sum solver by taking the values from the two text boxes and after clicking the button, it should post the result in the text box below. However it is not doing that.
I also want the program to change how a problem is solved using the dropdown menu with the mathematical symbols.
Thanks.
I think you're after something like this
function myFunction() {
var result = document.getElementById('answer'),
operator = document.getElementById('problem').value,
add1 = document.getElementById('num1').value,
add2 = document.getElementById('num2').value,
ans = 0;
switch (operator) {
case '+':
ans = (parseInt(add1) + parseInt(add2));
break;
case '-':
ans = (parseInt(add1) - parseInt(add2));
break;
case 'x':
ans = (parseInt(add1) * parseInt(add2));
break;
case '÷':
ans = (parseInt(add1) / parseInt(add2));
break;
}
result.value = ans;
}
instead of using if statements, and creating different functions, just have one function and determine the operand.
Edit: Also, watch out for your variable declarations. 'ans', 'add1' and 'add2' weren't being declared which resulted in global variables being created
The problem should be with the line
var result = document.getElementById('answer').value;
Try the below snippet
var result=document.getElementById('answer');
ans = (parseInt(add1)+parseInt(add2));
result.value=ans;
http://jsfiddle.net/2W5za/1/
You have a few issues. Not sure what you were going for with the if but remove it. Also, set the value of a textbox with value not innerHTML.
function myFunction() {
var result = document.getElementById('answer');
add1 = document.getElementById('num1').value;
add2 = document.getElementById('num2').value;
ans = (parseInt(add1)+parseInt(add2));
result.value = ans;
}
http://jsfiddle.net/LjqMJ/
Regarding the first part of the question (and that for which this question is titled), one problem I see is this line of code right here:
var result = document.getElementById('answer').value;
What is the type of result? Later on you treat it as if it is a DOMElement with result.innerHTML = ans; by assuming it has a property innerHTML. However because you used .value it's in fact a string which will not have innerHTML.
Regarding the second part, you can assert which function is selected in the <select> by looking at it's .value. The <option> tags will always exist, regardless of if they are selected or not.
Speaking more broadly, I highly recommend you check out using the debugger in either chrome or firefox. That will allow you to drop a breakpoint in your code, and figure out if the value is being computed correctly, and see what it is attempting to write to, all interactively.
Chrome:
https://developers.google.com/chrome-developer-tools/docs/javascript-debugging
Firefox:
https://developer.mozilla.org/en-US/docs/Tools/Debugger
<!DOCTYPE html>
<html>
<head></head>
<body>
<input type="text" id="num1" />
<select id="problem">
<option value="add">+</option>
<option value="sub">-</option>
<option value="mul">x</option>
<option value="div">%</option>
</select>
<input type="text" id="num2" />
<br />
<input type="submit" onclick="myFunction();" />
<br />
<input type="text" id="answer" readonly />
<script type="text/javascript">
function myFunction()
{
var e = document.getElementById("problem");
var sOperation = e.options[e.selectedIndex].value;
add1 = document.getElementById('num1').value;
add2 = document.getElementById('num2').value;
var ans;
if (!isNaN(add1) && !isNaN(add2)){
if(sOperation=='add'){
//Add
ans = parseInt(add1)+parseInt(add2);
} else if (sOperation=='sub') {
//Subtract
ans = parseInt(add1)-parseInt(add2);
} else if (sOperation=='mul') {
//Multiple
ans = parseInt(add1) * parseInt(add2);
} else if (sOperation=='div') {
//Divide
ans = parseInt(add1) / parseInt(add2);
}
document.getElementById("answer").value = ans;
} else {
alert("Please enter numeric values only");
return false;
}
}
There are many things wrong with your code. However, to fix your problem, change = ans to = ans.toString();
You see, in javascript integers and strings cannot change to each other's values without a conversion (kind of like a brother and sister refusing to share), so toString() is used for a conversion to String.
The other thing to change is innerHTML to value, because you are dealing with text boxes.
HTML
<input type="text" id="num1" />
<select id="problem">
<option id="add">+</option>
<option id="sub">-</option>
<option id="mul">x</option>
<option id="div">÷</option>
</select>
<input type="text" id="num2" />
<br />
<input type="submit" onclick="myFunction();" />
<br />
<input type="text" id="answer" readonly />
JavaScript
function myFunction() {
var result = document.getElementById('answer');
var operator = document.getElementById('problem').value;
var add1 = document.getElementById('num1').value;
var add2 = document.getElementById('num2').value;
var ans;
if (!isNaN(add1) && !isNaN(add2)) {
//Addition
if (operator == '+')
{
ans = (parseInt(add1) + parseInt(add2));
}
//Subtraction
else if (operator == '-') {
ans = (parseInt(add1) - parseInt(add2));
}
//Multiplication
else if (operator == 'x') {
ans = (parseInt(add1) * parseInt(add2));
}
//Division
else if (operator == '÷') {
ans = (parseInt(add1) / parseInt(add2));
}
//Result
result.value = ans;
} else {
alert("Please enter numeric values only");
return false;
}
}
Fiddle Demo

Javascript Converter Coding Error ~ Showing Bug

the converter is not showing up an answer when I input value into the forms. It shows up pop-up alert "You must enter a number between 32 and 40" ~Thanks
<HTML>
<HEAD>
<TITLE>Bra Size to Chest Size Converter - CM</TITLE>
<SCRIPT LANGUAGE="JavaScript">
function CalculateSum(Atext, Btext, form)
{
var A = BratoNum(Btext);
var B = parseFloat(CuptoNum(Btext));
form.Answer.value = A + B;
}
function ClearForm(form)
{
form.input_A.value = "";
form.input_B.value = "";
form.Answer.value = "";
}
function BratoNum(str)
{
switch(str.toUpperCase()) {
case "32": return 70;
case "34": return 75;
case "36": return 80;
case "38": return 85;
case "40": return 90;
default: alert('You must enter a number between 32 and 40!');
return 'X';
}
}
function CuptoNum(str)
{
switch(str.toUpperCase()) {
case "A": return 4;
case "B": return 5;
case "C": return 6;
case "D": return 7;
case "E": return 8;
case "F": return 9;
default: alert('You must enter a letter between A and F!');
return 'X';
}
}
// end of JavaScript functions -->
</SCRIPT>
</HEAD>
<BODY>
<P><FONT SIZE="+2">Bra Size to Chest Size Converter</FONT></P>
<FORM NAME="Calculator" METHOD="post">
<P>Enter Bra Size: <INPUT TYPE=TEXT NAME="input_A" SIZE=8></P>
<P>Enter Cup Size: <INPUT TYPE=TEXT NAME="input_B" SIZE=8></P>
<P><INPUT TYPE="button" VALUE="Get Chest Size" name="AddButton" onClick="CalculateSum(this.form.input_A.value, this.form.input_B.value, this.form)"></P>
<P>Your Chest Size is <INPUT TYPE=TEXT NAME="Answer" SIZE=8> inch</P>
<P><INPUT TYPE="button" VALUE="Clear" name="ClearButton" onClick="ClearForm(this.form)"></P>
</FORM>
</BODY>
</HTML>
var A = BratoNum(Atext);
You are passing Btext instead!
Actually you are passing invalid
argument to BratoNum function. That is
why it always going into default case'
var A = BratoNum(Atext);
// Here I have changed the argument , which you suppose to pass.
;

Categories