javascript concat() , want to concat 5 different value of string - javascript

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

Related

Im making calculator and when i add numbers 1+1 in my input i get answer 1. why

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

Retrieving number value from input instead of object

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

Trouble with adding numbers in Javascript?

I want to add the price of some books when each one checked but I have a problem.
It just adds a string. For example, when I select a book(10$), the price becomes 10 and when I select another book(20$) it becomes 1020, and so on...
My code :
For book one :
<input
name="bookList"
type="checkbox"
id="bookList_1"
onChange="
if (document.getElementById('bookList_1').checked) {
document.getElementById('priceDes').innerHTML=' total: ';
document.getElementById('price').innerHTML+=10;
}
"
value="book1"
>
For book two :
<input
name="bookList"
type="checkbox"
id="bookList_2"
onChange="
if (document.getElementById('bookList_2').checked) {
document.getElementById('priceDes').innerHTML=' total: ';
document.getElementById('price').innerHTML+=20;
}
"
value="book1"
>
And the price and priceDes are <p> tags ...
Thanks for your solutions ;)
It's because you're concatenating strings, instead of adding numbers. '10'+'20' gives '1020' and not 30.
Try:
document.getElementById('price').innerHTML=parseInt(document.getElementById('pr‌​ice').innerHTML)+10;
Be careful with this though, it would only work if your p tags have only the numbers inside their HTML. parseInt('10$') gives 10 but parseInt('$10') gives NaN. You can experiment with number-type input tags.
document.getElementById('price').innerHTML=Number(document.getElementById('price').innerHTML)+20;
InnerHTML is a string. The + operator is also the String concatenate operator in JavaScript. So, "cast" the values first.
Easy way to "cast" numerical strings in JavaScript: multiply by 1:
var rv = 1*a.innerHTML + 1*b.innerHTML;
Or, use the Number constructor:
var rv = Number(a.innerHTML) + Number(b.innerHTML);

Algorithm to transform a base 10 number to an any base number

I made this javascript program to convert base 10 number into another base number (smaller than 10). I would like to know why isn't the program responding.
Number to transform:<input type="text" id="number" /><br />
Base to transform to:<input type="text" id="basen" /><br />
<input type="submit" onclick="transform()" value="Transform" />
<script>
function transform()
{
var i=0;
var a;
var b;
var c;
var e;
var t=0;
var pui;
while(Math.pow(basen.value,i) <= number.value)
{
i++;
}
var pui=i-1;
while(pui>=0)
{
a=1;
while(Math.pow(basen.value,pui)*a <= number.value-t)
{
a++;
}
b=a-1;
e=10^pui;
t+=b*e;
pui--;
}
document.write(pui);
}
</script>
As Eric Jablow commented, ^ in JavaScript is a bitwise XOR operator. You want to use Math.pow(number, power) instead.
However, your whole algorithm could be replaced by the built-in Number.toString. for example:
(5).toString(4); // "11"
Also:
You have a syntax error here:
b=a-1:
^ -- should be a semicolon, not a colon
This kind of error can be easily spotted if you keep your browser console open when testing.
Your code relies on some magic performed by browsers, that automatically create variables based on HTML elements ID attributes. Don't do that, use document.getElementById to get element references.
OK, it's pretty simple.
pui is an integer value.
Last time into the second loop is when pui = 0.
Then you decrement pui, making it -1.
Then you output pui, and that is where your -1 comes from ;)

length does not work after multiplication

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);

Categories

Resources