I want to make a Calculator in JS. I'm new to JS and I don't get it why it isn't working. In the Browser Console I get undefined if I call add().
getInputAsNumber(...) should retrieves the input value from the field with the ID passed as Parameter
writeResult() writes the calculated result to the output field and is used in all operations
"use strict";
function add() {
let operator1;
let operator2;
getInputAsNumber(operator1, operator2);
let summe = operator1 + operator2;
writeResult(summe);
}
function getInputAsNumber(op1, op2) {
op1 = document.getElementById("op1").value;
op2 = document.getElementById("op2").value;
}
function writeResult(result) {
let outputElement = document.getElementById("output1");
outputElement.innerHTML = Number.result;
}
<form>
<h1>Calculator with Buttons</h1>
<label>Operand 1:</label>
<input id="op1" type="number">
<br>
<br>
<label>Operand 2:</label>
<input id="op2" type="number">
<br>
<br>
<label>Operators: </label>
<button>+</button>
<button>-</button>
<button>*</button>
<button>/</button>
<br>
<br>
<div id="result">
<label>Result: </label>
<output id="output1"></output>
</div>
</form>
You are passing op1 and op2 as a referenced parameter, but they are actually called by value (which means, that they aren't changed when changing inside of the function). You get undefined because operator1 and operator2 are only declared (not initialized!).
You can modify your function so that it returns both operators (instead of passing them):
function add() {
let {operator1, operator2} = getInputAsNumber();
let summe = operator1 + operator2;
writeResult(summe);
}
function getInputAsNumber() {
const op1 = document.getElementById("op1").value;
const op2 = document.getElementById("op2").value;
return {operator1: parseFloat(op1), operator2: parseFloat(op2)};
}
function writeResult(result) {
let outputElement = document.getElementById("output1");
outputElement.innerHTML = result;
}
<h1>Calculator with Buttons</h1>
<label>Operand 1:</label>
<input id="op1" type="number">
<br>
<br>
<label>Operand 2:</label>
<input id="op2" type="number">
<br>
<br>
<label>Operators: </label>
<button onClick="add()">+</button>
<button>-</button>
<button>*</button>
<button>/</button>
<br>
<br>
<div id="result">
<label>Result: </label>
<output id="output1"></output>
</div>
This function returns an object consisting of operator1 and 2 and using the object unwrapping (left side of the getInputAsNumber call) you can easily fetch the two values.
Additionally: just reading the values of the input field (.value) retrieves a string (!), adding two strings in JavaScript means concatination ("2" + "2" = "22"), so you need to parse them first.
The main issues I can see with your code is that:
you need to either pass op1 and op2 more directly, or [as below] set them globally so that they don't need to be passed at all
you can just use result, not Number.result [why the Number. in the first place?]
you might need to parse the inputs from string to number using parseInt
Then, if you add onclick attributes to your buttons or use enventListener, you can make the calculator work fully
"use strict";
var operator1;
var operator2;
function calcOp(operator) {
getInputAsNumber();
var op;
if (operator == 'add') {
writeResult(operator1 + operator2);
} else if (operator == 'sub') {
writeResult(operator1 - operator2);
} else if (operator == 'mul') {
writeResult(operator1 * operator2);
} else if (operator == 'div') {
writeResult(operator1 / operator2);
}
}
function getInputAsNumber() {
operator1 = parseInt(document.getElementById("op1").value);
operator2 = parseInt(document.getElementById("op2").value);
}
function writeResult(result) {
let outputElement = document.getElementById("output1x");
outputElement.value = result;
}
<h1>Calculator with Buttons</h1>
<label>Operand 1:</label>
<input id="op1" type="number">
<br>
<br>
<label>Operand 2:</label>
<input id="op2" type="number">
<br>
<br>
<label>Operators: </label>
<button onclick="calcOp('add');">+</button>
<button onclick="calcOp('sub');">-</button>
<button onclick="calcOp('mul');">*</button>
<button onclick="calcOp('div');">/</button>
<br>
<br>
<div id="result"><label>Result: </label><output id="output1x"></output></div>
I changed your add function to calcOp because all the operations would have very similar, but if you just wanted to have add :
function add() {
getInputAsNumber();
let summe = operator1 + operator2;
writeResult(summe);
}
[Also, as one of the comments mentioned, if you wrap it as a form the way you did, it will likely disappear after any operation. Just div will look the same and not disappear]
Related
I was making a password generator while learning javascript. Is there a way to call the checked radio button using a value or do I switch to getElementbyId while calling.
My HTML body-
<div class="container">
<p>Please select the type of Password you want to generate:</p>
<form id="new-form">
<input type="radio" id="wp" name="radio" class="redio" value="0" />
<label for="wp">Weak Password</label><br />
<input type="radio" id="sp" name="radio" class="redio" value="1" />
<label for="sp">Strong Password</label><br />
<input type="radio" id="ssp" name="radio" class="redio" value="2" />
<label for="ssp">Super Strong Password</label>
<br />
<input type="submit" id="btn" value="Generate Password" />
</form>
<div id="display" type="text" readonly="true"></div>
</div>
My javascript-
class password{
constructor(){
this.ucl="ABCDEFGHIJKLMNOPQRSTUVWXYZ"
this.lcl="abcdefghijklmnopqrstuvwxyz"
this.num="1234567890"
this.spc = "!##$%^&*()"
}
weakpassword(){
let arr = [this.ucl, this.lcl]
let pass = ""
for(let i=0;i<8;i++){
let random1= Math.floor(Math.random()*arr.length)
let random2= Math.floor(Math.random()*arr[random1].length)
pass= pass + arr[random1][random2]
}
return pass
}
strongpassword(){
let arr = [this.ucl, this.lcl, this.num]
let pass = ""
for(let i=0;i<14;i++){
let random1= Math.floor(Math.random()*arr.length)
let random2= Math.floor(Math.random()*arr[random1].length)
pass= pass + arr[random1][random2]
}
return pass
}
superstrongpassword(){
let arr = [this.ucl, this.lcl, this.num, this.spc]
let pass = ""
for(let i=0;i<20;i++){
let random1= Math.floor(Math.random()*arr.length)
let random2= Math.floor(Math.random()*arr[random1].length)
pass= pass + arr[random1][random2]
}
return pass
}
}
let display = document.getElementById("display");
let btn = document.getElementById("btn");
let radio = document.getElementsByClassName("redio");
let a = new password()
btn.addEventListener("click",()=>{
let b;
// if(document.getElementById('wp').checked){
// b= a.weakpassword()
// }
if(radio[0].checked){
b= a.weakpassword()
}
else if(radio[1].checked){
b= a.strongpassword()
}
else if(radio[2].checked){
b= a.superstrongpassword()
}
display.value= b
})
Here, I am getting an error-
Uncaught TypeError: Cannot read properties of null (reading 'addEventListener')
I'm trying to call the checked radio option value but getting an error 'Cannot read properties of null'.
I wrote a code to change values in Fahrenheit to Celsius using Javascript.
<p id = "result"> </p> // The result will appear here
<script>
function toCelsius(f) {
return (f-32) * 5/9;
}
document.getElementById("result").innerHTML = toCelsius(77);
</script>
I checked this code, and it works on my Eclipse.
However, instead of putting the value directly, I want to input a number in Fahrenheit and change that into Celsius.
I added the following.
<form id="frm1">
Enter a number : <input type="text" name=fahrenheit> <br>
<input type=button" onclick="toCelsius(frm1)" value="change"> // I need some help for handling parameter here
</form>
I want to make it as simple as possible like below.
Could anyone give me some tips on how to handle an input parameter?
I spotted a few problems.
There were some syntax issues in writing HTML attributes
The code that changes innerHTML of result won't get invoked when the button is clicked. Rather, it'll get invoked only once, the first time the script is run. To fix this, I placed that line in a function which would be called when the button is clicked. Please look at the change button action.
<p id="result"></p>
<script>
function toCelsius(f) {
return (f - 32) * 5 / 9;
}
function changeClicked() {
var input = document.getElementById("fahrenheit").value;
if (parseInt(input) === null) return;
document.getElementById("result").innerHTML = toCelsius(input);
}
</script>
<form id="frm1">
Enter a number : <input type="text" id="fahrenheit" name="fahrenheit"> <br>
<input type="button" onclick="changeClicked()" value="change">
</form>
Add an event listener for the button then call your toCelsius() function with passing the input value to it.
function toCelsius(f) {
return (f - 32) * 5 / 9;
}
document.getElementById('btn_change').addEventListener('click', function() {
var fahrenheit = document.getElementsByName('fahrenheit')[0].value;
document.getElementById('result').innerHTML = toCelsius(fahrenheit);
});
<form id="frm1">
Enter a number : <input type="text" name=fahrenheit> <br>
<input type="button" id="btn_change" onclick="toCelsius(frm1)" value="change">
</form>
<p id="result"> </p>
// Give input tag an id of "number"
Enter a number : <input type="text" name=fahrenheit id ="number"> <br>
// Then,
<script>
let number = document.getElementById("number").value;
function toCelsius(f) {
return (f-32) * 5/9;
}
document.getElementById("result").innerHTML = toCelsius(number);
</script>
<!-- The result will be displayed here -->
<p id="result" style="min-height: 20px"></p>
<input type="number" name="fahrenheit">
<input type="button" class="convert-to-celsius-btn" value="Convert to C">
<script>
var convertBtn = document.querySelector(".convert-to-celsius-btn");
var fahrenheitInput = document.querySelector("input[name=fahrenheit]");
var resultEl = document.querySelector("#result")
function toCelsius(f) {
return (f-32) * 5/9;
}
function convertToCelsius() {
var fahrenheit = fahrenheitInput.value;
// input validatation code goes here ...
// next convert to celsius
var celsius = toCelsius(fahrenheit)
// now show the value in the DOM
celsius = celsius.toFixed(2);
resultEl.textContent = celsius + " C"
}
convertBtn.addEventListener("click", convertToCelsius);
</script>
My full code can be found here: http://pastebin.com/t3JCBRrX
I made an easy calculation script for my website. I'd like two modifications but I can't seem to do it.
This is what I have now:
The function:
var ap,result;
function setValue() {
ap = Number(document.getElementById('ap').value);
}
function bereken(){
setValue();
result = (((ap*275)/(ap*275))*1200+(ap*275) || 0).toFixed(e);
document.getElementById('e').value = result;
}
The form:
<label for="e" id="answer">Kosten: </label>
<input type="field" name="Antwoord" id="e" disabled><br>
<input type="button" onclick="bereken()" value="Bereken">
I'd like to prefix the result with a euro sign (result is '€123' instead of '123').
I would also like the result to be just plain text, instead of a disabled input field.
Any help would be greatly appreciated, as I'm just a beginner. Thanks!
edit: the calculation is that complicated because I don't want the answer to be '1200' when '0' has been entered
See this FIDDLE
Just insert the value with '€' appended
document.getElementById('e').innerHTML = '€'+result;
Also you can change the disabled input to label if you want it to be plain text
var ap, result;
function setValue() {
ap = Number(document.getElementById('ap').value);
}
function bereken() {
setValue();
result = (((ap * 275) / (ap * 275)) * 1200 + (ap * 275) || 0).toFixed(e);
document.getElementById('e').innerHTML = '€' + result;
}
<input type='text' id='ap' placeholder='enter value' />
<label for="e" id="answer">Kosten:</label>
<label type="field" name="Antwoord" id="e" disabled></label> <br>
<input type="button" onclick="bereken()" value="Bereken">
change document.getElementById('e').value = result; to document.getElementById('e').value = "€"+result;.
change disabled to readonly.
Try this:
JS Code:
var ap,result;
function setValue() {
ap = Number(document.getElementById('ap').value);
}
function bereken(){
setValue();
result = (((ap*275)/(ap*275))*1200+(ap*275) || 0).toFixed(e);
document.getElementById('e').innerHTML = result;
}
HTML Code:
<input type="text" id="ap"/>
<label for="e" id="answer">Kosten: </label>
<span>€</span><span id="e"> </span><br>
<input type="button" onclick="bereken()" value="Bereken"/>
For my code, I am trying to call 2 parameters into a function. Once you have left the 2nd input box, and multiply the 2 numbers passed through and put it in the third text box. if either of the first 2 input boxes are empty, then color them light red. This is my code so far, what am I missing?
Javascript:
function multiply(one, two) {
if(one==""){
this.style.color='red';
}
if(two==""){
this.style.color='red';
}
else{
txt1=one * two;
return txt1;
}
}
HTML5:
First Value: <input type="text" name="mFirst" />
Second Value: <input type="text" name="mLast" onblur="multiply(mFirst.value, mLast.value)" />
Multiplication of First and Second Value: <input type="text" name="answer">
<input … onblur="multiply.call(this,this.form.elements.mFirst.value,this.form.elements.mLast.value)" >
function multiply(one, two) {
if(one && two){
this.form.elements.answer.value = one * two;
} else {
this.style.color='red';
}
}
Empty strings are non-truthy values, thus one && two will only be true if neither value is an empty string.
Using call allows you to set the value of this used inside the function.
Demo: http://jsfiddle.net/b5Ltt/
You might want to look at the HTML5 <output> element.
You are not passing this to your multiply() function.
If you want to change this.style you can pass this as an argument.
Also, you should change mFirst.value to this.form.elements.mFirst.value and the same for mLast.value
HTML:
First Value: <input type="text" name="mFirst" />
Second Value: <input type="text" name="mLast" onblur="multiply( this , mFirst.value, mLast.value)" />
Multiplication of First and Second Value: <input type="text" name="answer">
JavaScript:
function multiply( _this, one, two) {
var txt1 = 0;
if(one=="" || two==""){
// Should set both colors to red
_this.form.elements.mFirst.style.color = 'red';
_this.form.elements.mLast.style.color= 'red';
}else{
// parse float in the case of a decimal and set de
one = parseFloat(one);
two= parseFloat(two);
txt1 = one * two;
_this.form.elements.answer.value = txt1;
}
}
First Value: <input type="text" name="mFirst" id="mFirst" />
Second Value: <input type="text" name="mLast" id="mLast" onblur="multiply()" />
Multiplication of First and Second Value: <input type="text" name="answer" id="answer" />
function multiply()
{
var num_one = document.getElementById('mFirst').value;
var num_two = document.getElementById('mLast').value;
if(typeof num_one === 'number' && typeof num_two === 'number')
{
document.getElementById('answer').value = (parseInt(num_one) * parseInt(num_two));
}
else
{
document.getElementById('answer').style.color = 'red'; // not recommended method
}
}
Using a similar note, why this doesn't work?
function monetaryfields()
{
if (multiply) { total.value = unitary.value * quantity.value; }
else { unitary.value = total.value / quantity.value; }
}
<form>
<ul>
<li>Quantity: <input type="text" name="quantity" onblur="monetaryfields.call(true)" /></li>
<li>Unitary: <input type="text" name="unitary" onblur="monetaryfields.call(true)" /></li>
<li>Total: <input type="text" name="total" onblur="monetaryfields.call(false)" /></li>
</ul>
</form>
Im having trouble with this javascript. here is a n example
window.onload = initPage;
var euro;
var convert;
function initPage()
{
document.getElementById("convertButton").onclick = calcAnswer();
document.getElementById("conversionType").onchange = calcAnswer();
}
function calcAnswer()
{
//alert(document.getElementById("conversionType").value);
var value1 = document.getElementById("amount").value;
var conversionType = document.getElementById("conversionType").value;
//alert(conversionType);
if(var value = document.getElementById("conversionType").value=="polish");
document.getElementById("answer").value=(value1-32)/9*5;
else
document.getElementById("answer").value=value1*9/5+32;
}
here is the html
<h1>Currency Converter</h1>
<form name="convert">
Choose which currency you would like to convert to the Euro:
<select id="conversionType">
<option value="polish">Polish Zloty</option>
<option value="ukraine">Ukraine Hryvnia</option>
</select>
</br>
</br>
<hr>
Amount:<input id="amount" type="text" />
<input id="convertButton" type="button" value="Convert->"/>
To:
<input id="answer" type="text" name="answer" readonly="readonly"/>
</form>
im using an old temperature converter and havent changed that part part but even that part is not working.
For starters, these two lines are wrong:
document.getElementById("convertButton").onclick = calcAnswer();
document.getElementById("conversionType").onchange = calcAnswer();
Change them to:
document.getElementById("convertButton").onclick = calcAnswer;
document.getElementById("conversionType").onchange = calcAnswer;
You want to assign a function reference to onclick and onchange, not actually call the function and assign the return value.
Then, fix the if statement in calcAnswer like this:
function calcAnswer()
{
var amount = document.getElementById("amount").value;
var conversionType = document.getElementById("conversionType").value;
var answerElement = document.getElementById("answer");
//alert(conversionType);
if(conversionType == "polish") {
answerElement.value = (amount-32)/9*5;
} else {
answerElement.value = amount*9/5+32;
}
}
Should be
document.getElementById("convertButton").onclick = calcAnswer;
document.getElementById("conversionType").onchange = calcAnswer;
(without the parens)
You just need to reference the function, not execute it.