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
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>
I want to create a form where I will perform an operation with the values entered by the user, but when the function runs, I get NaN return. Thank you in advance for the help.
function test() {
var age = document.getElementsByName("person_age").value;
var weight = document.getElementsByName("person_weight").value;
var size = document.getElementsByName("person_size").value;
document.getElementById("result").innerHTML = weight + size + age;
}
<form>
<input type="text" name="person_age">
<input type="text" name="person_size">
<input type="text" name="person_weight">
<input type="button" value="calculate" onclick="test();">
</form>
<h3 id="result"></h3>`
Output:
NaN
When I get the values from the user and run the function, I get NaN feedback. how can i solve this problem.
There are multiple errors that you have to correct
1) When you use getElementsByName, It will return NodeList array like collection. So you have to get the element by using index as:
var age = document.getElementsByName( "person_age" )[0].value;
2) If you need sum of all three value then you have to convert it into Number type because document.getElementsByName( "person_age" )[0] give you value in String type. So you can do as:
+document.getElementsByName( "person_age" )[0].value
function test() {
var age = +document.getElementsByName("person_age")[0].value;
var size = +document.getElementsByName("person_size")[0].value;
var weight = +document.getElementsByName("person_weight")[0].value;
document.getElementById("result").innerHTML = weight + size + age;
}
<form>
<input type="text" name="person_age">
<input type="text" name="person_size">
<input type="text" name="person_weight">
<input type="button" value="calculate" onclick="test();">
</form>
<h3 id="result"></h3>
Just a Suggestion: You can use Document.getElementById if you want to directly access the value. Just add an ID property in your element. It will return a string value, convert that to int and you're good to go.
function test() {
var age = document.getElementById("person_age").value;
var weight = document.getElementById("person_weight").value;
var size = document.getElementById("person_size").value;
document.getElementById("result").innerHTML = parseInt(weight) + parseInt(size) + parseInt(age);
}
<form>
<input type="text" name="person_age" id="person_age">
<input type="text" name="person_size" id="person_size">
<input type="text" name="person_weight" id="person_weight">
<input type="button" value="calculate" onclick="test();">
</form>
<h3 id="result"></h3>
getElementsByName will always return an array-like nodelist so, if you were to use it you would need to access the first index [0]. Instead add a class to each input and use querySelector to target it.
The value of an input will always be a string (even if the input is type "number"), so you need to coerce it to a number, either by using Number or by prefixing the value with +.
So, in this example I've updated the HTML a little by adding classes to the inputs, and changing their type to "number", and removing the inline JS, and updated the JS so that the elements are cached outside of the function, an event listener is added to the button, and the values are correctly calculated.
// Cache all the elements using querySelector to target
// the classes, and add an event listener to the button
// that calls the function when it's clicked
const ageEl = document.querySelector('.age');
const weightEl = document.querySelector('.weight');
const sizeEl = document.querySelector('.size');
const result = document.querySelector('#result');
const button = document.querySelector('button');
button.addEventListener('click', test, false);
function test() {
// Coerce all the element values to numbers, and
// then display the result
const age = Number(ageEl.value);
const weight = Number(weightEl.value);
const size = Number(sizeEl.value);
// Use textContent rather than innerHTML
result.textContent = weight + size + age;
}
<form>
<input type="number" name="age" class="age" />
<input type="number" name="size" class="size" />
<input type="number" name="weight" class="weight" />
<button type="button">Calculate</button>
</form>
<h3 id="result"></h3>`
I trying to make a calculator but I have the problem with the "dot" because give me advertisement like this...
"The specified value "." cannot be parsed, or is out of range."
This is my code...
numberDot.addEventListener('click', function() {
numberDot = '.' ;
input.value = input.value + numberDot;
console.log(typeof(input.value));
console.log(input.value);
});
This is one way to do it
Use type="number" inputs and radio buttons to choose the operation. That helps the person to enter numbers. You can also use type="text"
The important part is the conversion from string data into numeric values
When you read data from the value property of an input, the data is returned as a string. It can be converted to a number using parseInt (for integers) or parseFloat (for floating point). If it can't be parsed, NaN (Not a Number) is returned. To test for NaN, use isNaN().
For example:
let x = "kittens";
let n = parseInt(x);
if (isNaN(n)) {
console.log(x + " is not a number");
}
The important part of this example is the conversion of numbers and figuring out which operation to perform.
// get the elements in the DOM
let numberOne = document.getElementById("numberOne");
let numberTwo = document.getElementById("numberTwo");
let output = document.getElementById("output");
let calculator = document.getElementById("calculator");
// every time the calculator values change
calculator.addEventListener('change', function(evt) {
// get the values from the number inputs and try to convert them to floating point
let valueOne = parseFloat(numberOne.value);
let valueTwo = parseFloat(numberTwo.value);
// if both numbers are numbers (this is not 100% accurate)
if (!isNaN(valueOne) && !isNaN(valueTwo)) {
// create a variable to store the result
let value = 0;
// get the radio buttons
let ops = calculator['operation'];
// use the selected radio button to determine the operation
switch (ops.value) {
case '+':
value = valueOne + valueTwo;
break;
case '-':
value = valueOne - valueTwo;
}
// display the result
output.textContent = value;
}
});
<form id="calculator">
<!-- first number -->
<input id="numberOne" type="number" placeholder="1.0" step="0.01" min="0" max="10">
<br>
<!-- radio buttons for operations -->
<label for="add">Add
<input type="radio" name="operation" value="+">
</label>
<label for="subtract">Subtract
<input type="radio" name="operation" value="-">
</label>
<br>
<!-- second number -->
<input id="numberTwo" type="number" placeholder="1.0" step="0.01" min="0" max="10">
</form>
<!-- to display the result -->
<output id="output"></output>
For those who still end up here with the above error from the browser. Generally, you will get this error when inserting the string into the input field of the type number. Check the Input field type attribute. This should do the trick.
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}}
I'm trying to get an autosum from fields, the issue is that if the total of fields are without value the script is not working correctly, and also if there are more than 7 fields again the script is not working.
here is the javascript:
function getTotal()
{
var value01 = document.getElementById('value01').value;
var value02 = document.getElementById('value02').value;
var value03 = document.getElementById('value03').value;
var value04 = document.getElementById('value04').value;
var value05 = document.getElementById('value05').value;
var value06 = document.getElementById('value06').value;
var value07 = document.getElementById('value07').value;
// Add them together and display
var sum = parseInt(value01) + parseInt(value02) + parseInt(value03) + parseInt(value04) + parseInt(value05) + parseInt(value06) + parseInt(value07);
document.getElementById('sum_total').value = sum;
}
inputs:
<input type="text" id="value01" />
<input type="text" id="value02" />
<input type="text" id="value03" />
here is starting to be added with a button more input fields.
<input type="text" id="+" />
<input type="text" id="++" />
<input type="button" value="Add Them Together" onclick="getTotal();" />
my question is, how can i get an auto + on var value01 02 03 etc.
Any help is appreciated.
Your question is not very clear and so I'm not too sure what you are wanting to do so feel free to offer clarification for optimum assistance. On that note, based off of what you have provided, I have two things to point out:
1) Your ID of "+" is not valid. Per the HTML 4 spec:
ID and NAME tokens must begin with a letter ([A-Za-z]) and may be
followed by any number of letters, digits ([0-9]), hyphens ("-"),
underscores ("_"), colons (":"), and periods (".").
2) Instead of creating a different var containing each value, I would recommend creating a function that you can use within a for loop that will determine the sums of each incremental input. This is more DRY and helps simplify things if the number of inputs were to grow.
function getValues(id){
return document.getElementById(id).value;
}
The pure JavaScript solution below begins with one input box and will add additional inputs with the click of a button, which I believe is what you're looking for. You can modify the number of initial input boxes accordingly, but it should give you an idea.
Javascript:
var max = 1;
function getValues(id){
var result = document.getElementById(id).value;
return (result ? result : 0);
}
function addInput(){
max++;
var input = '<input type="text" id="value'+ max +'" />';
document.getElementById("valuesContainer").innerHTML += input;
}
function getTotal(){
var sum = 0;
for(var i=1; i <= max; i++){
sum = sum + parseFloat(getValues("value" + i));
}
document.getElementById("total").innerHTML = sum;
}
HTML:
<div id="valuesContainer">
<input type="text" id="value1" />
</div>
<input type="button" value="Add Value" id="addMore" onclick="addInput();" />
<input type="button" value="Calculate Total" onclick="getTotal();" />
<div id="total"></div>
Demo: http://jsfiddle.net/Y4xgU/