Questions about javascript variable, need help~ - javascript

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()"

Related

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 = ....

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

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>

radio button .checked to perform a math expression using user input javascript

I have two textboxes where a user enters a number into each one and then clicks a radio button to select the mathematical operation to be performed upon the calculate button.This is for a homework assignment, so only javascript and html
are being used, no jquery. Currently when I click the button, nothing appears to happen and I am getting no console errors...
HTML
<div>
<p>Enter two numbers, select a math, then click the button.<br>
The answer will be shown below.</p>
<form>
1st number: <input type="text" name="number1">
2nd number: <input type="text" name="number2">
<br>
<input type="radio" name="add">Add <br>
<input type="radio" name="subtract">Subtract <br>
<input type="radio" name="multiply">Multiply <br>
<input type="radio" name="division">Division <br>
<input type="button" name="calc" onclick="calculate()" value="Calculate"> <br>
</form>
<p id="math_res"></p>
</div>
Javascript
function calculate(){
var num1 = parseInt("document.getElementsByName('number1').value;", 10);
var num2 = parseInt("document.getElementsByName('number2').value;", 10);
var add = document.getElementsByName("add");
var sub = document.getElementsByName("subtract");
var multi = document.getElementsByName("multiply");
var divis = document.getElementsByName("division");
var res = document.getElementById("math_res").innerHTML;
if (add.checked == true){
res = num1 + num2;
}
else if ( sub.checked == true){
res = num1 + num2;
}
else if (multi.checked == true){
res = num1 * num2;
}
else if (divis.checked == true){
res = num1 / num2;
}
}
I thought my function would take the input from the two text boxes and convert the user input to an integer and assign them to variable num1 and num2. Then assign each radio button to a variable to reduce typing of document.get...
that each if statement would check to see if that radio but was checked. If true perform calculation if false move to next if statement and display the results in a paragraph element.
where did I go wrong?
You have a couple of issues.
getElementsByName returns a collection of elements, not a single element so:
var add = document.getElementsByName("add");
will assign undefined to add. But you don't need to use it, just reference the controls as named properties of the form. Pass a reference to the button from the listener:
<input type="button" name="calc" onclick="calculate(this)" value="Calculate">
Then in the function get the form:
function calculate(element) {
var form = element.form;
Now just do:
var num1 = parseInt(form.number1.value, 10);
and so on, which also fixes the other issues you have with referencing the controls.
Also, radio buttons need to have the same name so that only one is selectable, so as Felix says, give them all the same name and differentiate on value (or class or some other attribute value). You'll need to loop over them to find out the operation to perform, so the HTML might be:
<input type="radio" name="operation" value="add">Add <br>
<input type="radio" name="operation" value="subtract">Subtract <br>
<input type="radio" name="operation" value="multiply">Multiply <br>
<input type="radio" name="operation" value="division">Division <br>
Then to get the operation:
var radios = form.operation;
var op;
for (var i=0; i<radios.length; i++) {
if (radios[i].checked) {
op = radios[i].value;
break;
}
}
Now check the value of op to work out whether to add, subtract, etc.
Here's a quick example, I don't recommend inline scripts like this but it's handy for playing.
<form>
<input type="radio" name="operation" value="add">Add <br>
<input type="radio" name="operation" value="subtract">Subtract <br>
<input type="radio" name="operation" value="multiply">Multiply <br>
<input type="radio" name="operation" value="division">Division <br>
<input type="button" onclick="
var form = this.form;
var radios = form.operation;
var op;
for (var i=0; i<radios.length; i++) {
if (radios[i].checked) {
op = radios[i].value;
break;
}
}
form.selectedOperation.value = op || 'No operation selected';
" value="Get selected operation">
<input type="text" readonly name="selectedOperation"><br>
<input type="reset">
</form>
There are a few issues I can notice.
1.
getElementsByName returns a NodeList, which is Array-like. You need to retrieve the first element in the NodeList before accessing its value. For example,
document.getElementsByName('number1')[0].value
2.
You are passing a literal code string to parseInt. You should write something like
parseInt(document.getElementsByName('number1')[0].value, 10);
3.
The code var res = document.getElementById('math_res').innerHTML stores a reference to the innerHTML of the element. When you assign res = num1 + num2 for example, you are simply overwriting the reference, instead of actually altering the innerHTML. To correct this,
var elem = document.getElementById('math_res');
// later...
elem.innerHTML = num1 + num2;
4. You are incorrectly defining multiple radio buttons with different names. In order for the browser to render them as a "radio button group" where only one can be selected, they must have the same name, but different "value" attributes. See RobG's answer or the Plunkr below for an example of how to define the radio button group and extract its value using JavaScript.
A working version of your code is here.
Edit Please note that these are minimal edits to make your code work. RobG's answer shows a more correct way of extracting the values of form fields.
Here is my version, hope it helps you.
<!DOCTYPE html>
<html>
<body>
<div>
<p>Enter two numbers, select a math, then click the button.<br>
The answer will be shown below.</p>
<form>
1st number: <input type="text" name="number1" id = 'number1'>
2nd number: <input type="text" name="number2" id = 'number2'>
<br>
<input type="radio" name="button" id = 'add' >Add <br>
<input type="radio" name="button" id = 'substract'>Subtract <br>
<input type="radio" name="button" id = 'multiply'>Multiply <br>
<input type="radio" name="button" id = 'division'>Division <br>
<input type="button" name="calc" onclick="calculate()" value="Calculate"> <br>
</form>
<p id="math_res"></p>
</div>
<script>
function calculate(){
//Obtaining the references to the text inputs
var number1 = parseInt(document.getElementById('number1').value);
var number2 = parseInt(document.getElementById('number2').value);
//Reference of the result Box
var resultBox = document.getElementById('math_res');
resultBox.innerHTML = '';
//Reference of the radio buttons
var buttonAdd = document.getElementById('add');
var buttonSubstract = document.getElementById('substract');
var buttonMultiply = document.getElementById('multiply');
var buttonDivision = document.getElementById('division');
//Make the magic
if(buttonAdd.checked == true){
resultBox.innerHTML = number1 + number2
}
else{
if(buttonSubstract.checked == true){
resultBox.innerHTML = number1 - number2
}
else{
if(buttonMultiply.checked == true){
resultBox.innerHTML = number1 * number2
}
else{
if(buttonDivision.checked == true){
resultBox.innerHTML = number1 / number2
}
}
}
}
}
</script>
</body>

Categories

Resources