I am trying to write a small program to determine the common factors between two numbers. I am having a problem getting the numbers, though. Here is my HTML code:
<p>Please input two numbers to find the common factors between them.</p>
First number:<input type="number" id="firstNumber"></br>
Second number:<input type="number" id="secondNumber"></br>
<button onclick="commonFactors(document.getElementById('firstNumber'),
document.getElementById('secondNumber'))">Submit</button>
However, instead of getting the numbers back, the console returns the following:
"<input type='number' id='firstNumber'>" "<input type='number'
id='secondNumber'>"
With the quotes. Can you tell me what I'm doing wrong?
Not sure it matters, but here's the JS:
function commonFactors(num1, num2) {
console.log(num1, num2);
var counter=Math.min(num1, num2);
var factors=[];
var k=0;
for (i=1; i<counter; i++) {
if (num1%i==0) {
if (num2%i==0) {
factors[k]=i;
}
}
k+=1;
}
};
because document.getElementById('firstNumber') is refering to the input, use +document.getElementById('firstNumber').value notice the + because the values you get from an input are of type string so we use the + to transform them to a number
Note: you can use a function instead of the + it's called parseInt() for integers and parseFloat() for float numbers
the result is
<button onclick="commonFactors(parseInt(document.getElementById('firstNumber').value),
parseInt(document.getElementById('secondNumbe').value)">Submit</button>
You want to get the value of the input, not the input itself :
document.getElementById('firstNumber').value
Related
input value = "1+1" but when i console.log(salyga) i am getting answer "1" . Also if I only put + in input and I console log it I am getting answer NaN, I don't understand why math is not working.
Also if I change input type="number" I'm getting this error (The specified value "+" cannot be parsed, or is out of range.)
let salyga = document.querySelector(".container__langai--salyga");
const vienas = document.querySelector("#vienas");
const one = +vienas.value
vienas.addEventListener("click", number1);
function number1() {
salyga.value += one
}
const lygu = document.querySelector("#lygu");
const equal = lygu.value
lygu.addEventListener("click", opLygu);
const plius = document.querySelector("#plius");
const plus = plius.value
plius.addEventListener("click", opPlius);
function opLygu() {
console.log(parseFloat(salyga.value))
}
function opPlius() {
salyga.value += plus
}
<input value="" type="text" placeholder="0" class="container__langai--salyga"></input>
<button id="vienas" class="number" value="1">1</button>
<button id="lygu" value="=" class="operator">=</button>
<button id="plius" value="+" class="operator">+</button>
To solve that problem, here's information. Text that are get from tags are always String, it doesn't matter even if you set the input's type to number, so convert it to either int or float by using the parseInt() and the parseFloat() respectively. A sample down below is shown to demonstrate the correct usage.
alert(parseInt(document.getElementById("input_name").value));
alert(parseFloat(document.getElementById("input_name").value));
Extracted from w3Schools:
This function determines if the first character in the specified string is a number. If >it is, it parses the string until it reaches the end of the number, and returns the number > as a number, not as a string.
Note: Only the first number in the string is returned!
So when you pass 1+1 to the parseFloat, it will return only 1.
Your code document.querySelector("#vienas"); produces a collection of DOM elements, not a single element as you seem to be expecting. It does not matter if only 1 element is found, it still returns a collection (with 1 item in it).
To get the item directly, use getElementById():
const vienas = document.getElementById("vienas");
I have text box with 5 digit numbers given by user,for ex:-if num2=(12345), I want to individual number to be subtract by 10. So the answer for 12345 will be 98765. I have used charAt() to separate the numbers and store in different variables. Then used concat() Which is not working. I am wondering their must be some different efficient approach to get required answer.
<input id="num2" type="text" /><br />
<input id ="comRanNum" type="text" /><br />
<input name="" type="button" onclick="check()" value="Click Here" />
function check()
{
var num2=document.getElementById("num2").value;
var temp0=10-num2.charAt(0);
var temp1=10-num2.charAt(1);
var temp2=10-num2.charAt(2);
var temp3=10-num2.charAt(3);
var temp4=10-num2.charAt(4);
var temp5=temp0.concat(temp1,temp2,temp3,temp4);
document.getElementById("comRanNum").value=temp5;
}
If your problem always involves 5 numbers, you could simply use 111110-num2. E.g., 111110-12345=98765. To solve the issue for a dynamic amount of numbers, you could make the number of 1s depend on how long the entered number is.
temp0 isn’t a string yet, so you can’t call concat on it. But if you’re converting it to a string anyways, why bother?
var temp5 = '' + temp0 + temp1 + temp2 + temp3 + temp4;
Since you specify exactly five digits, though, TVK’s answer is best. Math is always best.
var num = '12345';
var result = num.split('').map(function (item) {
return 10 - item;
}).join('');
console.log(result); // 98765
I am using AngularJS in one of our application.
In the code below, while loading the page the expression addition (number, valuetoadd) parses correctly and give output as 1+1=2 but while changing the input it doesn't parse correctly and it gives output as `1+2=12'.
Where do I need to change?
<div ng-controller='MathsController'>
<input type="range" min="0" max="100" step="1" value="1" ng-model='valuetoadd'/>
<p>Addition table of <b>{{valuetoadd}}</b></p>
<div ng-repeat='number in numbers'>
{{number}} + {{valuetoadd}} = {{ addition(number,valuetoadd) }}
</div>
</div>
<script type="text/javascript">
function MathsController($scope)
{
$scope.valuetoadd= 1;
$scope.numbers =[1,2,3,4,5,6,7,8,9,10];
$scope.addition = function(number,valuetoadd)
{
return number+valuetoadd;
}
}
</script>
May be number beging passed as a string.
Try:
$scope.addition = function(number, multiplier)
{
return + number + multiplier;
}
+ would convert the string into number.
EDIT:
Now, I see that multiplier is passed as string.
So IT has to be converted instead...
Sorry that I did not read the code carefully.
$scope.addition = function(number, multiplier)
{
return number + +multiplier;
}
Thank you #Artur for pointing this out.
Seems like the root of the problem lies here:
https://github.com/angular/angular.js/issues/1189
Also read this SO topic: Two-way binding with range and number input in AngularJS
As a workaround you can use the solutions proposed by thefrontender and tosh shimayama.
It's worth noticing, though, that it is the multiplier who requires parsing to integer, not the number. See my comment to your question.
Another quick fix is to multiply value by 1 before addition. This will force JavaScript to convert value from string to integer.
Example:
{{value*1 + 10}}
You need to coerce the variables into some sort of numeric type (values from HTML inputs are passed as string by default)
$scope.addition = function (number, multiplier) {
return number + parseInt(multiplier, 10);
}
I've got a javascript function that adds one to a quantity if the current value is less than another value. Here is the javascript function:
function addQty()
{
if(document.getElementById("quantity").value < document.getElementById("stock").value)
document.getElementById("quantity").value++;
else
return;
}
And here are the form elements that the values are taken from:
<input type='text' id="quantity" name='quantity' value ='0' />
<input type='hidden' id="stock" name="stock" value="<?php echo $adjustedStock; ?>" />
So basically the user can add one to their quantity of a product to order only if there is enough in stock.
Now, this works absolutely fine if the number in stock is 1-9, but if the stock level is in double digits, the maximum the user can add to their basket (ie the 'quantity' in the code) returns as the first digit + 1. So if the stock is 13 then the max quantity is 2, or if the stock is 63 the max quantity is 7.
I've tried converting the integer value of $adjustedStock to a string before it is used in the form as I read sometimes browsers can behave weirdly in this situation, but this didn't work. Any ideas why this is happening?
Thanks in advance!
The "value" attribute of an <input> is always a string. Thus your comparison is being done between two strings, which is not what you want.
Convert the values to numbers before comparing:
function addQty()
{
var qtyInp = document.getElementById('quantity'),
qty = parseInt(qtyInp.value, 10),
stk = parseInt(document.getElementById('stock').value, 10);
if (qty < stk)
qtyInp.value = qty + 1;
}
Form element values are strings. Use parseInt or convert to a number some other way.
You can use Math.min() for this purpose...
function addQty() {
var quantity = document.getElementById("quantity");
quantity.value = Math.min(+quantity.value + 1,
document.getElementById("stock").value);
}
This makes it very clear that you want the lesser of the incremented quantity or the total in stock.
Edit: Solution: http://jsfiddle.net/VnXtP/
Why dosent this work?
http://jsfiddle.net/uc7kT/
<input type="text" name="item_quantity" id="item_quantity" value="1" />
<input type="text" name="item_price" id="item_price" value="24998" hidden="hidden" />
$('#item_quantity').change(function() {
var quantity = $('#item_quantity').val();
var price = $('#item_price').val();
var total = quantity * price;
alert(total.length);
});
Length is defined for strings, not numbers. If you wish to do this as a mathematical operation, you must convert the input strings to numbers first. If you actually want the length of the number string (I don't know why you would), you need to convert the number to a string first:
$('#item_quantity').change(function() {
var quantity = parseInt($('#item_quantity').val(), 10);
var price = parseFloat($('#item_price').val());
var total = quantity * price;
alert(total.toString().length);
});
Use:
alert(total);
Instead of:
alert(total.length);
You may also want to consider converting the values of the input to a float, or integer value before performing the math.
http://jsfiddle.net/samliew/uc7kT/5/
total is a number. It does not have the property "length".
Try
alert(total);
I guess that is what you want.
In javascript a number is a number and a string is a string.
What can be sometimes confusing is that a number can automagically become a string when that is needed (for example adding a string to it).
Numbers do not have a length property, strings instead do. Also in javascript when you ask an object for a property that is not present normally you just get the undefined value.
var quantity = $('#item_quantity').val();
var price = $('#item_price').val();
item_quantity and item_price are text inputs, and you need to change it to Integer before you multiply. use parseInt() to do it.
var quantity = parseInt($('#item_quantity').val(),10);
var price = parseInt($('#item_price').val(),10);
and use alert(total); not alert(total.length);