Add Numbers from Each Line Break in Textarea with Javascript - javascript

I have the following in a textarea:
link|10000
link|25000
link|58932
I need to remove the characters before the "|" on each line and get the sum of the all the numbers
Any help will be greatly appreciated!

A short solution:
// Gets textarea content
var myTextareaText = document.getElementById('my-textarea-id').value;
// Uses array functions to simplify the process
let sum = myTextareaText.split('\n').map(x=>x.split('|')[1] * 1).reduce((a,b)=>a+b);
// Logs de result
console.log(sum);
What was done:
1) Break by line breaks : myTextareaText.split('\n')
2) Foreach line, break by "|", gets the second item and convert it to number: map(x=>x.split('|')[1] * 1)
3) Sum each element: reduce((a,b)=>a+b)

Another solution :
function myFunction() {
document.getElementById("demo").innerHTML = document.getElementById("myTextarea").value.split("link|").map(Number).reduce(function(a, b){return a+b; });
}
Calculate:<br>
<textarea id="myTextarea">
link|10000
link|25000
link|58932</textarea>
<p>Click the button to calculate.</p>
<button type="button" onclick="myFunction()">Calculate it</button>
<p id="demo"></p>

Get all numbers from the value using String#match method and calculate the sum using Array#reduce method.
var ele = document.getElementById('text');
// get the text area value
var res = ele.value
// get all digits combinations , if you want decimal number then use /\d+(\.\d+)?/g
.match(/\d+/g)
// iterate and calculate the sum
.reduce(function(sum, v) {
// parse the number and add it with previous value
return sum + Number(v);
// set initial value as 0
}, 0);
console.log(res);
<textarea id="text">link|10000 link|25000 link|58932
</textarea>

Related

Adding 1 incrementally to a string with numbers

$("#next").click(function() {
var text = $("#textbox").val();
var Numbers = text.substring(4, 8); //To get the 4 numbers
var Num = parseInt(Numbers, 10); //To convert to an integer?
var Add = +(Num).val() + 1; //Increment 1?
$("#textbox").val(Add); //Output final value
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="button" id="next" value="Increment" />
<br/>
<input type="text" id="textbox" value="ABC-123" />
I have a text box with a string of "ABC-1234" as the value and a button. I'm trying to add 1 to what's entered in the text box every time I click the button. I'm fairly new to programming but this is what I've come up with, which ends with the result of NaN.
The problem you want to solve is to add one to the numeric part of a mixed alpha-then-numeric text string.
Assuming your text will contain an alpha part, then a literal dash -, and finally a numeric part, it is easy to extract the numeric part using the String.split() method.
var text = $("#textbox").val();
var parts = text.split('-');
Now parts[0] is everything to the left of the dash and parts[1] is everything to the right. Just parse that into a number, add one, and add it back with the rest of the text, placing it back in the field.
$("#next").click(function() {
var text = $("#textbox").val();
var parts = text.split('-'); // Get the numbers in parts[1]
var num = parseInt(parts[1], 10); // Convert to an integer
num++; //Increment 1?
$("#textbox").val(parts[0] + '-' + num); //Output final value
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="button" id="next" value="Increment" />
<br/>
<input type="text" id="textbox" value="ABC-123" />
This is more flexible than text.substring(4, 8); because it will work with any length string and any length number, as long as there is a dash between them.
your code is almost right, but you have to change a few things to make it "right":
in dependency of the naming convention of javascript write the variables in lower(Camel)Case.
parseInt returns a primitive type of number. There is need for calling val() method on it! There is no function like that. Just use the variable itself
you have to prepend your increased number with the letters you chop of at the beginning.
All in all:
$("#next").click(function(){
var text = $("#textbox").val();
var numbers = text.substring(4); //To get all the numbers
var num = parseInt(numbers, 10); //To convert to an integer?
num = num + 1; //Increment 1?
$("#textbox").val(text.substring(0,4)+num); //Output final value
});

Splitting string into numbers by commas and then printing ends up skipping 1 y-value

This code was made to take x and y as input, split the strings by the commas, convert them to an integer, and then print out the string.
<body>
x: <input id="xv"> <br/>
y: <input id="yv">
<br/>
<div id="results">
<button onclick="action()">Go</button>
</div>
<script>
// javascript
var action = function(){
// separate by commas and place into array
var xvs = document.getElementById("xv").value.split(",");
var yvs = document.getElementById("yv").value.split(",");
// convert to an integer
for(var i=0, j=xvs.length; i<j; i++){
xvs[i] = parseInt(xvs[i]);
yvs[i] = parseInt(yvs[i]);
}
// print out results
document.getElementById("results").innerHTML = xvs + "<br/>" + yvs;
}
</script>
</body>
You would expect it to print out an identical copy of the input. However, instead, I get this result:
Input:
62,64,64,65,65,65,65,66,66,66,66,66,66,66,67,67,67,68,69,69
62,63,63,64,66,65,64,67,67,63,64,68,65,66,66,65,68,68.69,70
Output:
62,64,64,65,65,65,65,66,66,66,66,66,66,66,67,67,67,68,69,69
62,63,63,64,66,65,64,67,67,63,64,68,65,66,66,65,68,68,70,NaN
Does anyone know what is going on here?
Here is a jsfiddle link: https://jsfiddle.net/zs65x2e3/
Note that without putting it into an individual <script> tag the code does not work, as action() is considered undefined.
You have an error in your input,
Old:
62,64,64,65,65,65,65,66,66,66,66,66,66,66,67,67,67,68,69,69
62,63,63,64,66,65,64,67,67,63,64,68,65,66,66,65,68,68.69,70
Fixed:
62,64,64,65,65,65,65,66,66,66,66,66,66,66,67,67,67,68,69,69
62,63,63,64,66,65,64,67,67,63,64,68,65,66,66,65,68,68,69,70
You had a period instead of a comma.
The error is not because of the period. The looping has a problem.
You are running the loop on the length of the x input. If the y input has lesser inputs than x inputs then you will get NaN for the remaining iterations for y.
In your sample input the period caused the length of the inputs to be less than 1 hence you got 1 NaN at the end.

Javascript to randomly add/subtract to a number every second

What I want my function to achieve for my javascript function is for every second to either randomly subtract or add (a random number) to a number held in a div.
Here's what I have so far.
It doesn't work, it seems to append the number to the end of the div value (100), and also it doesn't take into account that I want it to either randomly add or subtract (it just adds at the moment)
setInterval(function(){
random = (Math.floor((Math.random()*15)+1));
currentnumber = document.getElementById('number');
document.getElementById('number').innerHTML = currentnumber + random;
}, 1000);
parse the current value as an integer, and then do another math.random and use it to decide negative or positive. Lastly, you need to use the innerHTML of currentnumber, not the entire node. So something like this should work:
setInterval(function(){
random = (Math.floor((Math.random()*15)+1));
var plusOrMinus = Math.random() < 0.5 ? -1 : 1;
random = random * plusOrMinus;
currentnumber = document.getElementById('number');
document.getElementById('number').innerHTML = parseInt(currentnumber.innerHTML) + random;
}, 1000);
WORKING FIDDLE
.innerHTML returns you a string which you'll need to parse into an integer to perform the addition or subtraction. Have a look at a number of methods listed in the following SO question
How do I convert a string into an integer in JavaScript?
currentnumber is a DOM object, and you can't add that to a number.
var div = document.getElementById('number');
div.innerHTML = Number(div.innerHTML) + 3;
Notice you are getting the innerHTML of the div, converting that to a Number(), adding your random number to it, and THEN setting your div.innerHTML to your new value.
http://jsfiddle.net/9LqQG/1/
Maybe try something like this:
setInterval(function(){
random = (Math.floor((Math.random()*15)+1));
currentnumber = parseInt(document.getElementById('number').innerHTML);
document.getElementById('number').innerHTML = currentnumber + random;
}, 1000);
Your currentnumber variable needs to get the innerHTML of the element, then parse the string into an integer.
jsFiddle

multiplying values

Im using the following method to add up text boxes. I have tried changing multiple things and cant seem to multiply two text box values! essential I want 2 text box that values are multiplied and displayed in a third text box. I want this value to be fluid aka change when the number changes! I was using this code because i may be multiplying more then one thing but if this is too much of a hassle i will live with just multiplying two at a time
The code im using to add is
<!--adding script #-->
<script>
$(document).ready(function(){
calculateSum();
//iterate through each textboxes and add keyup
//handler to trigger sum event
$(".txt").each(function() {
$(this).keyup(function(){
calculateSum();
});
});
});
function calculateSum() {
var sum = 0;
$("#sum").val(sum.toFixed(2));
//iterate through each textboxes and add the values
$(".txt").each(function() {
//add only if the value is number
if(!isNaN(this.value) && this.value.length!=0) {
sum += parseFloat(this.value);
}
});
//.toFixed() method will roundoff the final sum to 2 decimal places
$("#sum").html(sum.toFixed(2));
var total = document.getElementById("subtotal").value == "";
var total = document.getElementById("subtotal").value = sum;
}
<!--END adding script #-->
I tried setting the last line to
var times1 = document.getElementById(subtotal);
var times2 = document.getElementById(tax);
var equal = times1.value * times2.value;
and then changing var total1 = document.getElementById("total1").value = sum9; to var total1 = document.getElementById("total1").value = equal;
The text boxes id are subtotal and tax the box im trying to update is total1.
Thanks alot!
On every keyup, instead of getting all values and adding them explicitly, it is better to deduct the previous value of the corresponding input and add the current updated value to sum..
Also, if subtotal is correctly calculated, then the multipication operation what ever you have done should work correctly..
Please find the following jsfiddle where the sum is calculated as explained above along with multiplying the tax..
http://jsfiddle.net/tgvrs_santhosh/77uxK/1/
Let me know if you still face the issue..
Instead of this
if(!isNaN(this.value) && this.value.length!=0) {
I think a regular expression may work better because you are using string values
if (/^([-]?((\d+)|(\d+\.\d+)|(\.\d+)))$/.test(this.value)) {
I haven't tested this regex, but you should be able to find a good regex to test for valid numbers if this one doesn't work for some reason. Also I noticed you have a == after that getElementById.
I'm not totally certain it matters, but you can do sum += (this.value * 1) instead of parseFloat.
update
Try this var equal = ($("#subtotal").val() * 1) * ($("#tax").val() * 1);
I found your question very confusing, but I think what you're trying to say is you want to add up all the .txt fields to get a sub-total, then multiply that sub-total by a tax rate to get a total. If so, then you already know the sub-total is a valid number due to the way you calculate it, so then:
var tax = +$("#tax").val(), // get tax and convert to a number
total = tax ? sum * tax : sum; // if tax is a non-zero number multiply
// otherwise just take the sum as is
If your tax field is not an input then use .text() instead of .val().
Your existing code is rather more complicated than it needs to be. You can do this:
$(document).ready(function(){
calculateSum();
// you don't need an .each() loop, you can bind a keyup handler
// to all elements in the jQuery object in one step, and you don't
// need the anonymous function since it does nothing but call calculateSum:
$(".txt").keyup(calculateSum);
});
function calculateSum() {
var sum = 0,
val;
//iterate through each textboxes and add the values
$(".txt").each(function() {
// you don't need to test for NaN: just attempt to convert this.value
// to a number with the unary plus operator and if the result is not
// a number the expression val = +this.value will be falsy
if(val = +this.value)
sum += val;
});
$("#sum").html(sum.toFixed(2));
var tax = +$("#tax").val();
$("#total1").html((tax ? sum * tax : sum).toFixed(2));
}
For some reason the unary plus operator used throughout my answer is not widely known, but I prefer it to parseFloat().

Addition operation issues?

Hi i'm trying to do simple addition of two numbers in javascript. When i'm trying to get the two input element values, the result is coming in a concatenation of two numbers
Here is the code:
<html>
<title>
</title>
<head>
<script type="text/javascript">
function loggedUser() {
//Get GUID of logged user
//alert('success');
var x, y , result;
x = document.getElementById('value1').value;
y = document.getElementById('value2').value;
result=x+y;
alert(result);
document.getElementById('res').value = result;
}
</script>
</head>
<body>
<input type="text" id="value1"><br>
<input type="text" id="value2"><br>
<input type="text" id="res">
<input type="submit" value ="submit" onclick=loggedUser();>
</body>
</html>
The "+" operator is overloaded. If any of the parameters is a string, they are all converted to strings and concatenated. If the parameters are numbers, then addition is done. Form control values are always strings.
Convert the parameters to numbers first using one of the following:
x = Number(document.getElementById('value1').value);
or
x = parseInt(document.getElementById('value1').value, 10);
or
x = parsefloat(document.getElementById('value1').value);
or
x = +document.getElementById('value1').value;
or
x = document.getElementById('value1').value * 1;
and so on...
Oh, you can also convert it only when necessary:
result = Number(x) + Number(y);
etc.
The input fields contain strings. If you want to sum two numbers, you have to convert the strings to numbers before adding - otherwise you are just adding two strings. There are lots of ways to do that depending upon what you want to allow. Here's one:
var x, y , result;
x = Number(document.getElementById('value1').value);
y = Number(document.getElementById('value2').value);
result=x+y;
alert(result);
document.getElementById('res').value = result;
See it working here: http://jsfiddle.net/jfriend00/BWW2R/
document.getElementById('').value returns a string. You need to call parseInt on that to make it a number.
It's because x and y are actually strings, not numbers. The value field of the element is always a string, so x+y gives you the concatenation of x and y.
You can parse x and y as integers and add the result of the parsing: that will give you what you want.
The problem is when you take those values you are getting a string and in result you are doing a concatenation. You should use parseInt on both x and y like this:
x = parseInt(document.getElementById('value1').value);
y = parseInt(document.getElementById('value2').value);

Categories