Please advise how to ADD two numbers in JavaScript. I am not sure where I am going wrong here. Not clear how I need to convert string into integers or Numbers.
function add(){
"use strict";
num1 = parseInt(document.getElementById("firstNumber")).value;
num2 = parseInt(document.getElementById("secondNumber")).value;
parseInt(document.getElementById("result")).innerHTML =num1+num2;
}
<!doctype html>
<html>
<head>
<meta charset="UTF-8">
<title>Untitled Document</title>
<link href="MyStyle.css" rel="stylesheet" type="text/css">
<script src="myEvents.js"> </script>
</head>
<body>
<form>
1st Number : <input type="text" id="firstNumber" /><br>
2nd Number: <input type="text" id="secondNumber" /><br>
<input type="button" onClick="add()" Value="add" />
</form>
<p>Total:
<div id="result">
<input type="text"/> </div>
You're trying to parse the element as an int, and take the value of the int:
parseInt(document.getElementById("firstNumber")).value
Get the value from the element and parse that as an int:
parseInt(document.getElementById("firstNumber").value)
Also, parsing is unnecessary here (and doesn't really make sense when assigning to the property):
parseInt(document.getElementById("result")).innerHTML =num1+num2;
Just assign the property directly:
document.getElementById("result").innerHTML =num1+num2;
parseInt(document.getElementById("result")).innerHTML = num1 + num2;
This makes no sense. I’ll try to give an overview of the objects and functions you’re working with, because one or more of them seems to be being treated as a sort of magic.
Starting with elements:
var firstInput = document.getElementById("firstNumber");
var secondInput = document.getElementById("secondNumber");
document.getElementById is a function that takes a string, finds the element in your document with that id, and returns that element. Here, you’ve selected two <input> elements, which the above snippet assigns to firstInput and secondInput to distinguish them (<input>s) from numbers.
Each input has a value property, which is a string. Verify this in your browser’s console.
console.log(firstInput.value); // whatever you typed in the first box
console.log(typeof firstInput.value); // string
Onwards to parsing, then. parseInt is a function that parses a string into a number. You can try it out in your console, too:
var someString = "192";
var someNumber = parseInt(someString);
console.log(someNumber); // 192
console.log(typeof someNumber); // number
A quick type recap:
firstInput is an element
firstInput.value is a string
parseInt is a function that takes a string and returns a number
so you can use parseInt(firstInput.value) to get your first input’s value as a number. Writing that all out for both inputs,
var firstInput = document.getElementById("firstNumber");
var secondInput = document.getElementById("secondNumber");
var num1 = parseInt(firstInput.value);
var num2 = parseInt(secondInput.value);
Now that you have two numbers, you can add them:
var sum = num1 + num2;
Finally, to put the sum back into the result element, you just have to find that element as usual:
var resultElement = document.getElementById("result");
and assign the sum to its innerHTML.
resultElement.innerHTML = sum;
Recalling that parseInt takes a string and returns a number, now you should realize that no parseInt needs to be involved here. You have a number already – it’s sum. No string is involved.
All together with comments for easy reading, with each line performing fewer steps:
// Get <input> elements
var firstInput = document.getElementById("firstNumber");
var secondInput = document.getElementById("secondNumber");
// Parse the text entered in each into numbers
var num1 = parseInt(firstInput.value);
var num2 = parseInt(secondInput.value);
// Find their sum
var sum = num1 + num2;
// Get the output element
var resultElement = document.getElementById("result");
// Display the sum in the output element
resultElement.innerHTML = sum;
var num1 = parseInt(document.getElementById("firstNumber").value);
var num2 = parseInt(document.getElementById("secondNumber").value);
you have to define the variables and correct the parentheses
function add(){
"use strict";
var num1 = parseInt(document.getElementById("firstNumber").value);
//You need to define your variable before use.
var num2 = parseInt(document.getElementById("secondNumber").value);
console.log(document.getElementById("firstNumber"));
//this is a DOM object
console.log(typeof document.getElementById("firstNumber").value);
//this is a "string"
console.log(typeof parseInt(document.getElementById("firstNumber").value));
console.log(typeof +document.getElementById("firstNumber").value);
//quickly by use '+'
document.getElementById("result").innerHTML =num1+num2;
}
<!doctype html>
<html>
<head>
<meta charset="UTF-8">
<title>Untitled Document</title>
<link href="MyStyle.css" rel="stylesheet" type="text/css">
<script src="myEvents.js"> </script>
</head>
<body>
<form>
1st Number : <input type="text" id="firstNumber" /><br>
2nd Number: <input type="text" id="secondNumber" /><br>
<input type="button" onClick="add()" Value="add" />
</form>
<p>Total:
<div id="result">
<input type="text"/> </div>
Related
I would like to make major of basic math functions (addition, subtraction, ect.) to develop in JavaScript. Input parameters should be from HTML webpage, than do the in JavaScript and return result on the same HTML page.
function math() {
//document.getElementById("frm1").innerHTML;
var numb = document.getElementById("number").innerHTML;
var mod = document.getElementById("modifier").innerHTML;
console.log(numb);
console.log(mod);
var sum = 1; //numb + mod; //the 1 is a placeholder
console.log(sum);
sum = document.getElementById("sum").innerHTML;
}
<form id="frm1" action="randScript.js">
Number: <input type="int" name="number" id="number"><br> Modifiers: <input type="int" name="modifier" id="modifier"><br>
<input type="button" onclick="math()" value="Submit">
</form>
<p id="sum"></p>
Your form tag has an action attribute. This means the page will submit your information to the specified page. You can use jQuery to prevent the form from submitting.
$("#yourFormId").on("submit",function(event){event.preventDefault()})
You can also edit the forms action attribute itself to prevent it from submitting.
<form id="frm1" action"javascript:void(0);">
First: The type is text - there is no "int" thing
Number: <input type="text" name="number" id="number">
Second: if we read a bit documentation we figure also out how to get the alue into the JS part
var numb = document.getElementById("number").value;
here you can now do your further homework ;)
Third: Get things back:
either use another input. They work two ways.
document.getElementById("result").value="I did not do my homework alone"
or you place a div somewhere with an id
<div id="result"> </div>
and now you can really use innerHTML in js
document.getElementById("result").innerHTML="I am too lazy";
The rest and to put it all together is now up to you :) Have fun to study :)
Try that if you want to display the sum at the html element:
document.getElementById("sum").innerHTML = sum;
But a more precise Question would help!
There is no int type for form inputs in HTML you can learn here about input types: HTML form input types
<form id="frm1" >
Number1: <input type="number" name="number" id="number1"><br>
Number2: <input type="number" name="number" id="number2"><br>
Modifiers: <input type="text" name="modifier" id="modifier"><br>
<input type="button" onclick="math()" value="Submit">
</form>
<p id = "sum"></p>
<script type="text/javascript">
function math() {
var numb1 = parseInt(document.getElementById("number1").value);
var numb2 = parseInt(document.getElementById("number2").value);
var mod = document.getElementById("modifier").value;
if(mod == '+'){
var sum = numb1 + numb2;
}else if(mod == '-'){
var sum = numb1 - numb2;
}else if(mod == '*'){
var sum = numb1 * numb2;
}
if(sum === undefined){
alert('invalid inputs');
return false;
}else{
document.getElementById("sum").innerHTML = sum;
}
return true;
}
To retrieve inputs values properly use value rather then innerHtml.
Retrieved values are strings so you need to parse them to numbers (with parseInt) before using them in math.
function math() {
const numb = document.getElementById("number").value;
const mod = document.getElementById("modifier").value;
sum = document.getElementById("sum").innerText = parseInt(numb) + parseInt(mod);
}
I'm trying to increment multiple attributes on the page with two objects. I have tried to use .split() like so
var words = $('.block').find('input').attr('js-data-reveals').split(',');
var num = 0;
words += '_' + num++
$('.block').find('input').attr('js-data-reveals', words);
Which returns:
js-data-box="TYPE_0,FONT_1"
I want to search the whole page for this attribute and increment each set. e.g
js-data-box="TYPE_1,FONT_1"
js-data-box="TYPE_2,FONT_2"
You should do a little of work with regex and jQuery, bellow a full working example:
$(function(){
$('.block').find('input').each(function(){
var attrName = 'js-data-reveals';
var $el = $(this);
var attrs = $el.attr(attrName);
var data = attrs.split(',').map(function(item){
return item.replace(/\d+/, function(num){ return ++num});
});
$el.attr(attrName, data.join(','));
});
});
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
</head>
<body>
<div class="block">
<input js-data-reveals="TYPE_1,FONT_1" />
<input js-data-reveals="TYPE_5,FONT_2" />
</div>
<div class="block">
<input js-data-reveals="TYPE_8,FONT_0" />
<input js-data-reveals="TYPE_2,FONT_3" />
</div>
</body>
</html>
When you use String.split, you create an array. You must loop through each item in the array. The correct way to do this would be to do this:
var num = 0; // Set counter to 0
var newString = string.split(",").map(function(item) { // Split the string by ',' then loop through each item, replacing it with the correct value
return item + '_' + num;
}).join(','); // re-join the array of strings into a single string.
num++; // Increment counter.
EDIT:
It seems like you are asking for something else. In the case where you want to increment based on the current value, the correct way to do this would be to use a Regex as shown by Clieton. You still must use the Array.map function as split returns an array. The only difference is that you must use a regex to get the original number to increment.
In case you wish to collect the attributes and store them with a unique counter.
var num = 0;
var words = [];
var multiDimensional = [];
function CollectAttributes(params) {
console.log("Print attributes Line by Line");
$('.block').children('input').each(function () {
var attributes = $(this).attr('js-data-reveals').split(',');
var byLine = [];
for(i = 0; i < attributes.length; i++){
byLine.push(attributes[i]+ "_" + num);
words.push(attributes[i]+ "_" + num);
}
multiDimensional.push(byLine);
console.log(byLine.join()); // Result => Line by Line
num++;
});
console.log("Print attributes all in one array");
console.log(words); // Result => Basic array
console.log("Print attributes in multidimensional array");
console.log(multiDimensional); // Result => MultiDimensional array
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="block">
<input type="text" js-data-reveals="TYPE,FONT,ETC">
<input type="text" js-data-reveals="TYPE,FONT,ETC">
<input type="text" js-data-reveals="TYPE,FONT,ETC">
<input type="text" js-data-reveals="TYPE,FONT,ETC">
<input type="text" js-data-reveals="TYPE,FONT,ETC">
<input type="text" js-data-reveals="TYPE,FONT,ETC">
<input type="text" js-data-reveals="TYPE,FONT,ETC">
<input type="text" js-data-reveals="TYPE,FONT,ETC">
<input type="text" js-data-reveals="TYPE,FONT,ETC">
<input type="text" js-data-reveals="TYPE,FONT,ETC">
</div>
<input type="button" value="Test" onclick="CollectAttributes(this);">
Write a function minimum3 that returns the smallest number of 3 floating-point numbers. use the math.min function. Incorporate into a script that reads 3 values from user and determines the smallest.
<!DOCTYPE html>
<html>
<head>
<title>
Javascript Program to find smallest from 3 numbers</title>
<script type="text/javascript">
var num1;
var num2;
var num3;
var num1Int = parseInt(num1);
var num2Int = parseInt(num2);
var num3Int = parseInt(num3);
var num4 = Math.min(num1Int, num2Int, num3Int);
document.write(num4);
</script>
</head>
<body>
<form name=f1>
num1: <input type="textbox" name=num1><br>
num2: <input type="textbox" name=num2><br>
num3: <input type="textbox" name=num3><br><br><br>
<button onclick="num4">Smallest</button>
</form>
</body>
</html>
Write a function...
To start, you need to place the statements you wrote inside the body of a function that takes 3 floating point numbers. So, start by writing a simple function:
function minimum3(num1, num2, num3) {
return Math.min(num1, num2, num3);
}
Now you need to get the field values, parse the floating point numbers from them (for this you should use parseFloat, not parseInt) and pass them to your function. I would recommend that you do this prior to calling your function rather than doing it within your function body; this will keep your function generic enough to use again should you need to find the minimum of 3 numbers (you probably won't, but it's good practice):
// get the field values
var val1 = document.querySelector('[name="num1"]').value;
var val2 = document.querySelector('[name="num2"]').value;
var val3 = document.querySelector('[name="num3"]').value;
// parse the floating point numbers
var number1 = parseFloat(val1);
var number2 = parseFloat(val2);
var number3 = parseFloat(val3);
// pass them to your function
var minimum = minimum3(number1, number2, number3);
Math.min(a, b) returns a when a <= b and b otherwise.
In order to find the minimum of n numbers, you can organize it as a bracket tournament. For example, to find the minimum of the following 20 numbers,
[11, 8, 53, 46, 34, 55, 85, 12, 34, 87, 890, 22, 63, 12, 76, 8654, 345, 8, 9, 23]
you can start pairing them off and get the minimum of each pair.
[11, 8] -> 8
[53, 46] -> 46
[34, 55] -> 34
[85, 12] -> 12
[34, 87] -> 34
[890, 22] -> 22
[63, 12] -> 12
[76, 8654] -> 76
[345, 8] -> 8
[9, 23] -> 9
Now you have 10 numbers left, from which you can make 5 pairs to get 5 of the smallest 10 numbers. You can repeat this process until you have only two "candidate" pairs left, which necessarily includes the smallest number of the original set.
Hopefully this puts you in the right mindset to solve this problem.
Why limit it to only three known inputs when you could use any number...
const form = document.querySelector('form')
const inputs = form.querySelectorAll('input[type="number"]')
const out = document.querySelector('output')
form.addEventListener('input', e => {
out.value = Math.min(...Array.prototype.map.call(inputs, input => input.value))
}, false)
<form>
<p><input type="number"></p>
<p><input type="number"></p>
<p><input type="number"></p>
<p>Min = <output name="min"></output></p>
</form>
Try following script:
<form name=f1>
num1: <input type="text" name=num1 id="txtNum1"><br>
num2: <input type="text" name=num2 id="txtNum2"><br>
num3: <input type="text" name=num3 id="txtNum3"><br><br><br>
<button onclick="Calculatenum4();">Smallest</button>
</form>
<script type="text/javascript">
function Calculatenum4() {
var num1 = document.getElementById('txtNum1');
var num2 = document.getElementById('txtNum2');
var num3 = document.getElementById('txtNum3');
var num4 = Math.min(parseFloat(num1.value),
parseFloat(num2.value), parseFloat(num3.value));
alert(num4);
}
</script>
<!DOCTYPE html>
<html>
<body>
<p>Find minimum:</p>
<input id="numb1">
<input id="numb2">
<input id="numb3">
<button type="button" onclick="myFunction()">Submit</button>
<p id="demo"></p>
<script>
function myFunction() {
var x,y,z,text;
x = document.getElementById("numb1").value;
y=document.getElementById("numb2").value;
z=document.getElementById("numb3").value;
if (isNaN(x)) {
text = "Input not valid";
} else {
text = Math.min(x,y,z)
}
document.getElementById("demo").innerHTML = text;
}
</script>
</body>
</html>
Here is possible solution for you. First, you won't get anything on passing variable in onclick event, you need to pass method/function, like getNum();
second, you need to prevent form from proceeding submission, by returning false.
After that, you need to take the values from inputs. The way you did it, you will need to use document.getElementsByName, but since it would return an array, you would need to retrieve at least first index [0].
After that, the Math.min method compares between 2 possible values, so you would need first to compare first 2 values, then result from first two, and third value.
There is a more complex way to do this with multiple values comparison, but this is better way to help you understand.
After that, you cannot write to whole document results, but you need some container, or to output it in console using console.log.
In this case, you need something visible, so we use container with "results" ID, and document.getElementByID() method and innerHTML to write the output for results.
<!DOCTYPE html>
<html>
<head>
<title>
Javascript Program to find smallest from 3 numbers</title>
<script type="text/javascript">
function getMin(){
var num1 = document.getElementsByName('num1')[0].value;
var num2 = document.getElementsByName('num2')[0].value;
var num3 = document.getElementsByName('num3')[0].value;
console.log(num1, num2, num3);
var num1Int = parseInt(num1);
var num2Int = parseInt(num2);
var num3Int = parseInt(num3);
var num4 = Math.min(num1Int, num2Int);
num4 = Math.min(num4, num3);
document.getElementById('results').innerHTML = num4;
return false;
}
</script>
</head>
<body>
<form name=f1 onsubmit="return false;">
num1: <input type="textbox" name=num1><br>
num2: <input type="textbox" name=num2><br>
num3: <input type="textbox" name=num3><br><br><br>
<button onclick="getMin()">Smallest</button>
</form>
<div id="results"></div>
</body>
</html>
Change the input type="number" and apply with id of each input.And the get the value from id declare as variable. Finally passing to Math.min() function.
If type=number no need parseInt.else is a type=text use parseInt .input types
Change the onclick onlclick =num4() instead of onclick="num4" its function not a string.
<!DOCTYPE html>
<html>
<body>
<form name=f1>
num1: <input type="number" id="num1" name=num1><br>
num2: <input type="number" id="num2" name=num2><br>
num3: <input type="number"id="num3" name=num3><br><br><br>
<button onclick="num4()">Smallest</button>
</form>
<script>
function num4(){
var num1 = document.getElementById('num1').value;
var num2 =document.getElementById('num2').value;
var num3 =document.getElementById('num3').value;
var num4 = Math.min(num1, num2, num3);
console.log(num4);
}
</script>
</body>
</html>
You can write a function like this and return the result:
function minimum3(){
var num1 = document.getElementsByName('num1').value
var num2 = document.getElementByName('num2').value;
var num3 = document.getElementByName('num3').value;
var num4 = Math.min(num1,num2,num3);
return num4;
}
then change this the following on your code:
<button onclick="minimum3()">Smallest</button>
So the goal was to make a very simple two field form and use javascript to validate that only numeric values are entered in either field.
Two issues with my code: only the else condition of the functions that follow seems to execute. Even more confusingly it also executes just clicking in the other field when the fields are empty.
Help please?
The Javascript:
// 1. Validate that only a numeric value is entered
function validateMin() {
var min = document.getElementById("min").value;
if (isNaN(min)) {
var el1 = document.getElementById("valFailMin");
el1.textContent = "Ok";
} else {
var el1 = document.getElementById("valFailMin");
el1.textContent = "Only numbers";
}
}
function validateMax() {
var max = document.getElementById("max").value;
if (isNaN(max)) {
var el2 = document.getElementById("valFailMax");
el2.textContent = "Ok";
} else {
var el2 = document.getElementById("valFailMax");
el2.textContent = "Only numbers please";
}
}
The HTML:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<link rel="stylesheet" type="text/css" href="custom.css">
</head>
<body>
<div class="myForm">
<label for="min">Min</label><input id="min" type="number" placeholder="Type a min value" onblur="validateMin()"/><br>
<span id="valFailMin"></span>
</div>
<div class="myForm">
<label for="max">Max</label><input id="max" type="number" placeholder="Type a max value" onblur="validateMax()" /><br>
<span id="valFailMax"></span>
</div>
<div id="valSuccess"></div>
</body>
<script src="validate.js"></script>
</html>
isNaN() returns true, if the checked value is not a number, if it is a number, the return value is false. Also the argument is internally coerced to a number before checking it. In this coercion an empty string is evaluated to 0, which is a number, hence the check returns false.
A fix would be to add a not operator to the condition and detect empty value:
if (!isNaN(min) && min !== '') {...}
A general way to check, if a variable is a number:
var isNumber = (!isNaN(+variable) && isFinite(+variable));
In your function:
if (isNaN(min)) {
var el1 = document.getElementById("valFailMin");
el1.textContent = "Ok";
isNaN returns true if the value isn't a number, so this will return "Ok" where min isn't a number. Depending on the type of number you are after, a regular expression may be more appropriate:
if (/^\d+\.?\d*$/.test(min)) {
// min is an integer or float
}
This will return true for values like '5' or '12.3' but false for valid numbers like '1.23e4'.
The number validation function should be separate from the function to validate the fields, so:
function validNumber (value) {
return /^\d+\.?\d*$/.test(value);
}
Then the validation can be something like:
function validateNumberField(el) {
var errField = document.getElementById(el.id + 'Err');
errField.textContent = validNumber(el.value)? 'Ok' : 'Fail';
}
if you pass this from the listener and link the id (or name) of the input being checked to its related error field.
Some markup (simplified for posting):
Min<input id="min" type="number" placeholder="Type a min value"
onblur="validateNumberField(this)"><br>
<span id="minErr" style="color:red"></span><br>
Max<input id="max" type="number" placeholder="Type a max value"
onblur="validateNumberField(this)"><br>
<span id="maxErr" style="color:red"></span>
You may want to allow for an empty value and to remove leading and trailing white.
I have this code using angular js:
<!DOCTYPE html >
<html>
<head>
<title>Untitled Page</title>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.0.5/angular.min.js"></script>
<script type="text/javascript">
function TodoCtrl($scope) {
$scope.total = function () {
return $scope.x + $scope.y;
};
}
</script>
</head>
<body>
<div ng-app>
<h2>Calculate</h2>
<div ng-controller="TodoCtrl">
<form>
<li>Number 1: <input type="text" ng-model="x" /> </li>
<li>Number 2: <input type="text" ng-model="y" /> </li>
<li>Total <input type="text" value="{{total()}}"/></li>
</form>
</div>
</div>
</body>
</html>
I am able to do multiplication, division and subtraction but for addition, the code just concatenates the x and y values (i.e. if x = 3 and y = 4, the total is 34 instead of being 7)
What am I doing wrong?
If that is indeed the case then what is happening is the values that are being passed in for x and y are being treated as strings and concatenated. What you should do is convert them to numbers using parseInt
return parseInt($scope.x) + parseInt($scope.y);
or if you prefer brevity
return $scope.x*1 + $scope.y*1;
You want this:
return parseFloat($scope.x) + parseFloat($scope.y);
+ overrides string concatenation when you have 2 strings. You'll need to cast them to integers or floats explicitly. -,*,/ will all cast to numbers if possible.
That is because the concatenation has higher precedence over addition operation or the Plus (+) Operator.
Since, Minus Operator (-) works just fine , here is a Simple Hack!
<script type="text/javascript">
function TodoCtrl($scope) {
$scope.total = function () {
//Subtracting a Zero converts the input to an integer number
return (($scope.x - 0) + ($scope.y - 0));
};
}
</script>
You could as well do this:
<form>
<li>Number 1: <input type="text" ng-model="x" /> </li>
<li>Number 2: <input type="text" ng-model="y" /> </li>
<li>Total <input type="text" value="{{(x-0) + (y-0)}}"/></li>
</form>
Adding floating numbers in correct way
$scope.Total = parseFloat($scope.firstValue) + parseFloat($scope.secondValue);
$scope.Total = parseFloat($scope.Total.toFixed(2));
The $scope.Total now will display correctly in the view if binding with ng-model is applied
for example if you have
$scope.firstValue = 10.01;
$scope.firstValue = 0.7;
$scope.Total = parseFloat($scope.firstValue) + parseFloat($scope.secondValue);
The variable $scope.Total will be 10.709999999999999 and this is not correct!
Adding with parseFloat will not be enough for a correct value.
But if you apply
$scope.Total = parseFloat($scope.Total.toFixed(2));
The value will result correctly: $scope.Total = 10.71
Be careful will floating point numbers in javascript
Make input type as number, since it is addition operation
<input type="text" ng-model="x" />
<input type="text" ng-model="y" />
To add two numbers together I would parse the string for Integers and check for null:
function TodoCtrl($scope) {
$scope.total = function() {
var firstNum = parseInt($scope.firstNum)
var secondNum = parseInt($scope.secondNum);
if (!firstNum)
firstNum = 0;
if (!secondNum)
secondNum = 0;
return firstNum + secondNum;
}
}
I advise you to change the type of your input to "number", then, you will not need to parse it, angular will convert it automatically to interger. I did it and it works, without a scope, but only to declare your {{total}}