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}}
Related
function selectHighestNumber()
{
var valueFirstNumber;
var valueSecondNumber;
var valueThirdNumber;
var selectMaxNumber;
valueFirstNumber = document.getElementById("txtFirstNumberValue").value;
valueSecondNumber = document.getElementById("txtSecondNumberValue").value;
valueThirdNumber = document.getElementById("txtThirdNumberValue").value;
selectMaxNumber = Math.max(valueFirstNumber, valueSecondNumber, valueThirdNumber);
document.getElementById("selectRankingNumbersResults").innerHTML = selectMaxNumber;
}
function selectLowestNumber()
{
var valueFirstNumber;
var valueSecondNumber;
var valueThirdNumber;
var selectMinNumber;
valueFirstNumber = document.getElementById("txtFirstNumberValue").value;
valueSecondNumber = document.getElementById("txtSecondNumberValue").value;
valueThirdNumber = document.getElementById("txtThirdNumberValue").value;
selectMinNumber = Math.min(+valueFirstNumber, +valueSecondNumber, +valueThirdNumber);
document.getElementById("selectRankingNumbersResults").innerHTML = selectMinNumber;
}
<main class="fancy-border">
<form id="userNumberEntry">
<p><label for="txtFirstNumberValue">Enter your first number here:</label>
<input type="text" id="txtFirstNumberValue" maxlength="20" size="20"></p>
<p><label for="txtSecondNumberValue">Enter your second number here:</label>
<input type="text" id="txtSecondNumberValue" maxlength="20" size="20"></p>
<p><label for="txtThirdNumberValue">Enter your third number here:</label>
<input type="text" id="txtThirdNumberValue" maxlength="20" size="20"></p>
<p><input type="button"
value="Find the highest number"
id="btnSubmit"
onclick="selectHighestNumber();">
</p>
<p><input type="button"
value="Find the lowest number"
id="btnSubmit"
onlick="selectLowestNumber();">
</p>
<br>
<div id="selectRankingNumbersResults">
</div> <!--end of selectRankingNumberValues div-->
</form>
</main>
So very recently I came into a problem in my script where I was unsure why my Math min function was not working. I asked about that issue in a previous question and found that a spelling error was causing one of my functions to not work. Essentially, I have two functions, a math min, and a math max, both serving similar purposes. I am working in Html code, and use a script for my functions within my Html document. The purpose of this math min and math max function is that I have three text boxes to input numbers into, there are two buttons that will either serve to show the highest or lowest of these three values. My math max function works fine and shows the highest value, however, my math min function does not. It does not return any value at all. I have cross-checked my code to see if it was misspelled, spacing errors, or other mismatched words with the rest of my code but none of it seems to be the problem. This is how my math max and math min functions in my script look respectively.
function selectHighestNumber()
{
var valueFirstNumber;
var valueSecondNumber;
var valueThirdNumber;
var selectMaxNumber;
valueFirstNumber = document.getElementById("txtFirstNumberValue")
.value;
valueSecondNumber = document.getElementById("txtSecondNumberValue")
.value;
valueThirdNumber = document.getElementById("txtThirdNumberValue")
.value;
selectMaxNumber = Math.max(valueFirstNumber, valueSecondNumber,
valueThirdNumber);
document.getElementById("selectRankingNumbersResults").innerHTML =
selectMaxNumber;
}
function selectLowestNumber()
{
var valueFirstNumber;
var valueSecondNumber;
var valueThirdNumber;
var selectMinNumber;
valueFirstNumber = document.getElementById("txtFirstNumberValue")
.value;
valueSecondNumber = document.getElementById("txtSecondNumberValue")
.value;
valueThirdNumber = document.getElementById("txtThirdNumberValue")
.value;
selectMinNumber = Math.min(valueFirstNumber, valueSecondNumber,
valueThirdNumber);
document.getElementById("selectRankingNumbersResults").innerHTML =
selectMinNumber;
}
If anyone could help me understand where I might be going wrong, that would be greatly appreciated! I am very confused about what I could have coded wrong, so any insight/outlook is greatly appreciated!
Math.max and Math.min will return the largest/smallest value (or -Infinity/Infinity if no values are supplied) and then convert to a number if they're not already, this means that strings will first be compared as strings and not numbers ("123" > "3"), so you should first convert each value to a number.
Also I recommend batching up the whole process instead of getting each element separately, reading its value, converting it to a number, checking it's valid, passing it to the function. So try to do the whole thing in a loop of some sort.
document.querySelector("form").addEventListener("submit", function(event) {
event.preventDefault();
console.log("Max:" + getEdgeCase(true));
console.log("Min:" + getEdgeCase(false));
});
function getEdgeCase(flag) {
// get all the inputs in one go and convert them to an array
var inputList = [].slice.call(document.querySelectorAll("form input[type=\"number\"]"));
var inputList = inputList.map(function(input) {
// convert to number, if it's not a valid number and ends up as NaN then return 0
return +input.value || 0;
});
// get the right function and call apply (spreads an array into arguments)
return Math[flag ? "max" : "min"].apply(Math, inputList);
}
<form>
<input type="number" />
<input type="number" />
<input type="number" />
<input type="submit" />
</form>
If I change the symbols at {{ num1+num2+num3 }} with symbols for multiplication (*) or substraction (-) it works well. However, when trying to add by using the (+) it simply concatenates.
<div id="vue_mult">
<input type="number" v-model="num1" min="78" max="98" /> +
<input type="number" v-model="num2" min="78" max="98" /> +
<input type="number" v-model="num3" min="78" max="98" /> =
{{ num1+num2+num3 }}
</div>
<script>
const app = new Vue({
el:'#vue_mult',
data: {
num1:0,
num2:0,
num3:0
} //end data property
}) //end Vue object
</script>
</body>
</html>
It's because the value of each input are automatically strings (hell, everything is a string in HTML/HTTP), therefore being concatenated by default. I would do the summation on a method (or a computed property) and convert the values to integers during the operation. This also separates some concerns -- making your template arguably cleaner.
const app = new Vue({
el:'#vue_mult',
data: {
num1:80,
num2:80,
num3:80
},
methods: {
sum: function(nums){
let result = 0;
nums.forEach(function(n){ result += n * 1; });
return result
}
}
//end data property
}) //end Vue object
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.min.js"></script>
<div id="vue_mult">
<input type="number" v-model="num1" min="78" max="98" /> +
<input type="number" v-model="num2" min="78" max="98" /> +
<input type="number" v-model="num3" min="78" max="98" /> =
{{ sum([num1, num2, num3]) }}
</div>
</body>
</html>
You simply need to parse the string into number and than you're good to go.
Basically when you try to use + operator on string it does the concatenation not the addition.So to do mathematical operation you need to parse the string into numbers. something like this:-
{{ Number(num1) + Number(num2) + Number(num3) }}
Why it does work with the other symbols.
When you call other any other operator except addition it internally changes it number using toNumber function. so they work same as any normal number will.
let sub = `1`-`1`;
let mul = `1` * `2`;
let div = `1` / `1`;
console.log(sub);
console.log(mul)
console.log(div)
num1, num2 and num3 are strings, convert them to numeric first before adding:
{{ Number(num1) + Number(num2) + Number(num3) }}
There is a .number modifier for v-model directive which you can use in this kind of situations.
Here is an example:
https://codepen.io/bengu/pen/GRNXNbe
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);">
This seems embarrassing to ask even for a newbie like me, but I have a huge headache with displaying new value in the html input field after adding spaces between numbers in html input.
Basically, what I want to achieve is to add spaces between numbers in the input field after the user "unclicks" the input.
For example, 123456789123456789 would change to 12 3456 7891 2345 6789. I get the value of users input and add spaces where I want, but I just can't make it appear in the input field. My code looks like this:
'use strict';
$(document).ready(function (){var $inputTwo = $('#separateNumbers');
$inputTwo.change(function() {
var inputNumber = $inputTwo.val();
var separatedNumbers = [];
var part1 = inputNumber.substring(0, 2);
separatedNumbers.push(part1);
for (var i = 2; i < inputNumber.length; i += 4){
separatedNumbers.push(inputNumber.substring(i, i + 4))
}
var displayNumber = separatedNumbers.join(' ');
$inputTwo.val(displayNumber);
})
});
<body>
<div class="wrapper">
<div id="Task1_2">
<h1>Task 1.2</h1>
<label for="separateNumbers">Write more than 10 digits:</label><br/>
<input type="number" id="separateNumbers" placeholder=" i.e. 12345678901234567">
</div>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
</body>
I don't understand why this doesn't work. I tried to replace last code line with
document.getElementById('separateNumbers').value = displayNumber;
but then I got this in console:
The specified value "87 6178 1" is not a valid number.
The value must match to the following regular expression:
-?(\d+|\d+\.\d+|\.\d+)([eE][-+]?\d+)?.
This appears no matter what combination of numbers I put. Unfortunately I don't understand Regex yet, so I don't even know what would be a valid value...
a number does not have spaces in it. change your input to a type = text and it should work
change the type to text because adding space not work in the text format
$(document).ready(function() {
// Displaying new input value (adding spaces) -- Solution
$("#separateNumbers").change(function() {
$inputTwo = $('#separateNumbers');
var inputNumber = $inputTwo.val();
var separatedNumbers = [];
var part1 = inputNumber.substring(0, 2);
separatedNumbers.push(part1);
for (var i = 2; i < inputNumber.length; i += 4) {
separatedNumbers.push(inputNumber.substring(i, i + 4))
}
var displayNumber = separatedNumbers.join(' ');
$inputTwo.val(displayNumber);
});
});
<body>
<div class="wrapper">
<div id="Task1_2">
<h1>Task 1.2</h1>
<label for="separateNumbers">Write more than 10 digits:</label><br/>
<input type="text" id="separateNumbers" placeholder=" i.e. 12345678901234567">
</div>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
</body>
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>