Trying to access HTML calculator w/ Higher Order Function and Callbacks - javascript

I have been working through the w3 challenges and I thought I could write the solution out better than they provided.
I wanted to obey DRY principles, so I created a callback for dividing and one for multiplying and made the principle function a HOF for each callback. However, for some reason It's not working, nor is it throwing an error. I've reviewed my code and so far haven't had any luck resolving it.
In a perfect world the HTML inputs would be either multiplying or dividing the code. Yet, nothing is happening.
Any ideas?
var userMultiply = function() {
document.getElementById("result").innerHTML = num1 * num2;
}
var userDivide = function() {
document.getElementById("result").innerHTML = num1 / num2;
}
function userMaths(callBack) {
let num1 = document.getElementById('firstNumber').value;
let num2 = document.getElementById('secondNumber').value;
}
<form>
1st Number : <input type="text" id="firstNumber" /><br> 2nd Number: <input type="text" id="secondNumber" /><br>
<input type="button" onClick="userMaths(userMultiply)" Value="Multiply" />
<input type="button" onClick="userMaths(userDivide)" Value="Divide" />
<p>The result is: </p>
<span id="result"></span>
</form>
</body>

Several problems:
You never call the callback.
The variables num1 and num2 are local variables in userMaths, they can't be accessed from userMultiply and userDivide. You should pass them as parameters.
You should also convert the inputs to numbers with parseFloat(). Operators like * and / do this automatically, but you'll run into a problem when you add userAdd, because + will do string concatenation instead of addition.
You might also want to move the code that displays the result into userMaths, since it's the same for all operations.
var userMultiply = function(num1, num2) {
return num1 * num2;
}
var userDivide = function(num1, num2) {
return num1 / num2;
}
function userMaths(callBack) {
let num1 = parseFloat(document.getElementById('firstNumber').value);
let num2 = parseFloat(document.getElementById('secondNumber').value);
document.getElementById("result").innerHTML = callBack(num1, num2);
}
<form>
1st Number : <input type="text" id="firstNumber" /><br> 2nd Number: <input type="text" id="secondNumber" /><br>
<input type="button" onClick="userMaths(userMultiply)" Value="Multiply" />
<input type="button" onClick="userMaths(userDivide)" Value="Divide" />
<p>The result is: </p>
<span id="result"></span>
</form>

Related

Html form input to variable for use in a js function

<form onsubmit="calculos(); return false;">
<label for="gasto">
<span> Valor </span>
<input
required
type="number"
id="gasto"
class="gasto"
name="gasto"
placeholder="Valor.."
/>
</label>
<input type="submit" value="submit"/>
</form>
script trying to take that input into a variable for a function to
return that inpunt and * to print in web
<script language="javascript">
function calculos() {
document.getElementById("gasto").value;
var num1 = document.getElementById("gasto").value;
Honorarios = num1 * 0.3;
Escribania = num1 * 0.2;
sellos = num1 * 0.05;
return (Honorarios, Escribania, sellos);
console.log(gasto);
console.log(Honorarios);
console.log(Escribania);
console.log(sellos);
alert(gasto, Honorarios, Escribania, sellos);
}
calculos();
</script>
sorry if i dont explain good enough im learing html and js and wanted to make a calculator that you input a amount and the algorithm gives you back that amount * by 0.05 and others thanks
I edited your code, and removed the unnecessary lines, also moved the label HTML element which was badly placed, it works now, watch out for console log.
I also combined all results into a single string before alert line.
function calculos() {
document.getElementById("gasto").value;
var num1 = document.getElementById("gasto").value;
Honorarios = num1 * 0.3;
Escribania = num1 * 0.2;
sellos = num1 * 0.05;
console.log(Honorarios);
console.log(Escribania);
console.log(sellos);
let allOfThem = `Honorarios: ${Honorarios}
Escribania: ${Escribania}
sellos: ${sellos}`
alert(allOfThem);
}
//calculos(); This function SHOULD never be here, as it will be called everytime.
<form onsubmit="calculos(); return false;">
<label for="gasto">
<span> Valor </span>
</label> <!-- This was moved here to the right place, it was at the end of form -->
<input
required
type="number"
id="gasto"
class="gasto"
name="gasto"
placeholder="Valor.."
/>
<input type="submit" value="submit"/>
</form>

How do i clear information in a form?

I am doing my first javascript app (some kind of calculator, where you write 2 numbers and you can add them, substract them, multiply them and divide them) i want to make a button that lets you clear the numbers you typed, i have searched on the web but i can't find exactly how to do it; my code is this:
function addBy() {
num1 = document.getElementById("firstNumber").value;
num2 = document.getElementById("secondNumber").value;
document.getElementById("result").innerHTML = +num1 + +num2;
}
function substractBy() {
num1 = document.getElementById("firstNumber").value;
num2 = document.getElementById("secondNumber").value;
document.getElementById("result").innerHTML = +num1 - +num2;
}
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 clear() {
document.getElementById("result").innerHTML = "";
}
<form>
1st Number : <input type="number" id="firstNumber" /><br>
2nd Number: <input type="number" id="secondNumber" /><br>
<input type="button" onClick="addBy()" value="Add" /><br>
<input type="button" onClick="substractBy()" value="Substract" /><br>
<input type="button" onClick="multiplyBy()" Value="Multiply" /><br>
<input type="button" onClick="divideBy()" Value="Divide" /><br>
<input type="button" onClick="clear()" value="Clear" /><br>
</form>
can anyone help?
Because it seems like your aim is to have calculator-like functionality here, your clear() function just needs to clear the inputs on the page, as well as the result.
Similar to how you are getting the values for firstNumber and secondNumber, you can also set those values to an empty string.
function clear() {
document.querySelector("#firstNumber").value = "";
document.querySelector("#secondNumber").value = "";
document.querySelector("#result").innerHTML = "";
}
If you want to clear only inputs
Input Type Reset can do that,
Just add
<input type="reset" value="Clear"/>
Or
<button type="reset">Clear</button>
At your form and then whenever anyone clicks it, it will clear all the inputs taken from the user.
JavaScript Approach as a Function
function clear() {
document.getElementById('#form-id').reset();
}
If you want to clear inputs and the result
Javascript Function
function clear() {
document.getElementById('#firstNumber').value = '';
document.getElementById('#secondNumber').value = '';
document.getElementById('#result').innerHTML = '';
}
I hope it will work.

finding highest number in Javascript from user input

I have tried two different Javascript code to find the largest number from three user inputs. I am not getting the highest number from none of the codes. Please help!
HTML Code:
Assignment 1: <input type="text" name="num1"><br>
Assignment 2: <input type="text" name="num2"><br>
Assignment 2: <input type="text" name="num3"><br>
<input type="button" id="high" value="high" onclick="high()">
<input type="text" id="avg">
<p id="result"></p>
JavaScript Code(Try 1):
function high() {
let num1 = document.getElementsByName("num1")[0].value;
let num2 = document.getElementsByName("num2")[0].value;
let num3 = document.getElementsByName("num3")[0].value;
var avg = Math.max(Number(num1),Number(num2),Number(num3))
document.getElementById("result").innerHTML=avg;
JavaScript Code(Try 2):
function high() {
let num1 = document.getElementsByName("num1")[0].value;
let num2 = document.getElementsByName("num2")[0].value;
let num3 = document.getElementsByName("num3")[0].value;
if(Number(num1)>Number(num2) && Number(num1)>Number(num3))
{
document.getElementsByName("avg")[0].value = num1;
}
if(Number(num2)>Number(num1) && Number(num2)>Number(num3))
{
document.getElementsByName("avg")[0].value = num2;
}
if(Number(num3)>Number(num2) && Number(num3)>Number(num1))
{
document.getElementsByName("avg")[0].value = num3;
}
you are making things complex try this code .
Assignment 1: <input type="text" name="num1"><br>
Assignment 2: <input type="text" name="num2"><br>
Assignment 2: <input type="text" name="num3"><br>
<button onclick="high()">Submit</button>
<p id="result"></p>
<script>
function high(){
var arr = document.querySelectorAll("input");
var emptyarray = [];
arr.forEach((elem) => {
emptyarray.push(elem.value);
})
var max = Math.max.apply(null, emptyarray);
document.getElementById("result").innerHTML=max;
}
</script>
you will get the heighest number result , you can restrict the input field to just enter the number so that no one can add string instead of number and your code work fine .

My simple calculator is not working. I want to use event listener on button click event

I want to achieve following:
Create a simple calculator that adds, multiplies, subtracts, and divides two numbers.
Three text boxes that contain input number1, input number2, and result respectively
Four buttons, add, subtract, divide, and multiply respectively
Four functions add(), subtract(), multiply(), divide() to perform addition, subtraction, multiplication, and division respectively on the two input numbers.
Each function should display the result in the third(result) textbox.
Add "click" event listeners to all buttons and use the above function names as handlers
Input validation. Inside each handler function use the isNaN() function on textbox values to ensure that the user enters digits and not alphabets or other characters. Display an alert to inform the user.
Ensure that the user does not leave any textbox empty when clicking on any button. Use value="" to ensure this. Display an alert to inform the user.
my not working code is down below:
<html>
<body>
<h1> Calculator</h1>
<input type="text" id="textbox1" placeholder="Enter number 1" >
<input type="text" id="textbox2" placeholder="Enter number 2" >
<input type="text" id="textbox3" placeholder="Results" ><br><br>
<input type="button" id="button1" value="Add">
<input type="button" id="button2" value="Subtract">
<input type="button" id="button3" value="Multiply">
<input type="button" id="button4" value="Devide">
<script>
var button1 = document.getElementById("button1");
button1.addEventListener("click",add);
var button2 = document.getElementById("button2");
button2.addEventListener("click",subtract);
var button3 = document.getElementById("button3");
button3.addEventListener("click",multiply);
var button4 = document.getElementById("button4");
button4.addEventListener("click",devide);
function add(){
var num1 = parseInt(document.getElementById('textbox1').value);
var num2 = parseInt(document.getElementById('textbox2').value);
document.getElementById("textbox3").innerHTML = num1 + num2;
}
function subtract(){
var num1 = parseInt(document.getElementById('textbox1').value);
var num2 = parseInt(document.getElementById('textbox2').value);
document.getElementById("textbox3").innerHTML = num1 - num2;
}
function multiply(){
var num1 = parseInt(document.getElementById('textbox1').value);
var num2 = parseInt(document.getElementById('textbox2').value);
document.getElementById("textbox3").innerHTML = num1 * num2;
}
function devide(){
var num1 = parseInt(document.getElementById('textbox1').value);
var num2 = parseInt(document.getElementById('textbox2').value);
document.getElementById("textbox3").innerHTML = num1 / num2;
}
</script>
</body>
</html>
Text boxes don't have a meaningful innerHTML. Instead of document.getElementById("...").innerHTML = ..., use document.getElementById("...").value = ....

Questions about javascript variable, need help~

I put 5、4 into the blanks 1st Number、2nd Number, and clicked Multiply in the output. I am looking forward to get 20, but I got zero, why?
Here's the code (also on JSBin):
var num1 = document.getElementById("firstNumber").value;
var num2 = document.getElementById("secondNumber").value;
function multiplyBy() {
var c = num1 * num2;
document.getElementById("result").innerHTML = c;
}
var divideBy = function() {
var c = num1 / num2;
document.getElementById("result").innerHTML = c;
};
body {
margin: 30px;
}
<form>
1st Number :
<input type="text" id="firstNumber" />
<br>2nd Number:
<input type="text" id="secondNumber" />
<br>
<input type="button" onClick="multiplyBy()" value="Multiply" />
<button onClick=d ivideBy()>Divide</button>
</form>
<p>The Result is :
<br>
</p>
<p id="result"></p>
If you are using button & form you need to specify the type of button that is submit,button or reset. The default is submit which will submit the form.
Secondly there is a typo in
<button onClick=d ivideBy()>Divide</button>
instead it will be onclick = "devideBy()"
You need to use these two variable inside the function.Reason being when js is parsing at beginning it is setting the value to 0 as those inputs are empty & inside the function you are getting 0.
var num1 = document.getElementById("firstNumber").value;
var num2 = document.getElementById("secondNumber").value;
HTML
<form>
1st Number :
<input type="text" id="firstNumber" />
<br>2nd Number:
<input type="text" id="secondNumber" />
<br>
<input type="button" onClick="multiplyBy()" value="Multiply" />
<!--button type button -->
<button type = "button" onClick="divideBy()">Divide</button>
</form>
<p>The Result is :
<br>
</p>
<p id="result"></p>
JS
function multiplyBy() {
var num1 = document.getElementById("firstNumber").value;
var num2 = document.getElementById("secondNumber").value;
var c = num1 * num2;
document.getElementById("result").innerHTML = c;
}
var divideBy = function() {
var num1 = document.getElementById("firstNumber").value;
var num2 = document.getElementById("secondNumber").value;
var c = num1 / num2;
document.getElementById("result").innerHTML = c;
};
Working jsfiddle
Your first two lines run immediately when the page loads, not later when you click one of the buttons. So you get the values of the inputs as of when the page loads, which is "". * implicitly converts its operands to numbers, so "" becomes 0, and 0 * 0 is 0.
You want to get the .value from the input elements inside your click handlers, so you get the current value:
// Here we get the elements, but not their values
var num1input = document.getElementById("firstNumber");
var num2input = document.getElementById("secondNumber");
function multiplyBy() {
// Get the values as they are *now*
var c = num1input.value * num2input.value;
document.getElementById("result").innerHTML = c;
}
var divideBy = function() {
// Get the values as they are *now*
var c = num1input.value * num2input.value;
document.getElementById("result").innerHTML = c;
};
body {
margin: 30px;
}
<form>
1st Number :
<input type="text" id="firstNumber" />
<br>2nd Number:
<input type="text" id="secondNumber" />
<br>
<input type="button" onClick="multiplyBy()" value="Multiply" />
<button onClick=d ivideBy()>Divide</button>
</form>
<p>The Result is :
<br>
</p>
<p id="result"></p>
Side note: The value of an input is always a string. It happens that / and * will both implicitly coerce their operands to numbers, but if you did the same thing with + you'd get concatenation (one string appended to the end of the other), not addition. You want to convert your values to numbers. This answer discusses the various ways you can convert numeric strings to numbers in JavaScript.
Side note 2: As user2181397 pointed out, while the above will make your Multiply button work, there are two additional issues with your Divide button:
The default type of a button element is "submit", which will submit the form instead of just calling the click handler. Give type="button" (like you did on the input).
onClick=d ivideBy() should be onclick="divideBy()"

Categories

Resources