$("#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
});
Related
I can't seem to figure out why the subtraction is working in my code, but when I change the subtraction sign to an addition sign, I get a console error: Uncaught TypeError: undefined is not a function. Where is the error?
Here is a fiddle with the subtraction: http://jsfiddle.net/c8q7p6ac/
Here is a fiddle with the addition in place of the subtraction sign: http://jsfiddle.net/c8q7p6ac/1/
The subtraction sign and the addition sign are in the variable updatedNumber
HTML:
<div class="amount">$1000.00</div>
<input class="new-number" type="text">
<div class="button">Click</div>
jQuery:
$('.button').on('click', function(){
//get value of input
var newNumber = $('.new-number').val();
//get total number value
var totalNumber = $('.amount').text();
var getNumberOnly = totalNumber.indexOf('$') + 1;
var newTotalNumb = totalNumber.substr(getNumberOnly, totalNumber.length);
//add new number to total number
var updatedNumber = (newTotalNumb + newNumber).toFixed(2);
//and update total
$('.amount').html('$'+updatedNumber);
});
The subtraction works because JavaScript converts them to numbers. However, in case of addition, it converts them to strings as soon as one of the operands is a string.
You need to convert the string to a number:
var updatedNumber = (parseInt(newTotalNumb) + parseInt(newNumber)).toFixed(2);
While dealing with decimal points, you can also use parseFloat which will preserve the decimal points.
Here's the updated fiddle.
This question already has answers here:
Adding two numbers concatenates them instead of calculating the sum
(24 answers)
Closed 5 months ago.
I created a simple program that make the sum of two numbers BUT..
the program is concatenating instead, This is so confusing!
Can anyone help?
function calculate() {
var numberOne = document.querySelector(".first").value;
var numberTwo = document.querySelector(".second").value;
var sum = numberOne + numberTwo;
document.querySelector(".result").innerHTML = "The sum of the two numbers is : " + sum;
}
<!doctype html>
<html>
<body>
<p>Calculate sum of two numbers !</p>
Enter 1rst Number:<br>
<input type="number" class="first" placeholder=""><br><br> Enter 2nd Number:<br>
<input type="number" class="second" placeholder=""><br><br>
<input type="button" onclick="calculate()" value="calculate">
<p class="result"></p>
</body>
</html>
Here value gives you a string, hence the concatenation. Try parsing it as an Number instead:
var sum = parseInt(numberOne) + parseInt(numberTwo);
See the demo fiddle.
Javascript takes dom elements as string only by default. To make mathematical calculation, you need to typecast it to integer/float or convert to number.
parseInt(number) = number, truncates after decimal value
parseFloat(number) = number with decimal values
Number(number) = number with or without decimal
Your numberOne and numberTwo are strings, so you get concatenated strings when use + sign with two string.
Parse first to numbers then sum them. You can use parseInt() and parseFloat() functions for it.
var numberOne = '7';
var numberTwo = '8';
var sum = numberOne + numberTwo;
console.log(sum);
sum = parseFloat(numberOne) + parseFloat(numberTwo);
console.log(sum);
Use parseInt() for this, Check snippet below
function calculate() {
var numberOne = document.querySelector(".first").value;
var numberTwo = document.querySelector(".second").value;
var sum = parseInt(numberOne) + parseInt(numberTwo);
document.querySelector(".result").innerHTML = "The sum of the two numbers is : " + sum;
}
<p>Calculate sum of two numbers !</p>
Enter 1rst Number:<br>
<input type="number" class="first" placeholder=""><br><br>
Enter 2nd Number:<br>
<input type="number" class="second" placeholder=""><br><br>
<input type="button" onclick="calculate()" value="calculate">
<p class="result"></p>
Example , you can use this:
var numberOne:number = +document.querySelector(".first").value;
var numberTwo:number = +document.querySelector(".second").value;
var sum = numberOne + numberTwo;
You should use + Angular typeScript
It's just because value returns with string. So sum operation ends with concatenation.
you need to convert both those values.
user below code
var sum = parseFloat(numberOne) + parseFloat(numberTwo);
Who are using javascript in salesforce make sure
var a= 8 ;
var b =8 ;
var c = a+b;
This will give u result output = 88;
It is will just concatenate. If you want to add those two:
You should write logic as :
var a = 8;
var b = 8
var c = parseInt(a)+ parseInt(b);
This will give you the desired result of 16 , The same is the case with multiplication.
Hope this helps.
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>
I am bewildered as to why I cannot add three numbers together. Here is my HTML:
<div><label>Sales Price: </label>
<input type="number" name="sales_price" value="3">
</div>
<div><label>Incentives: </label>
<input type="number" name="incentives" value="2">
</div>
<div><label>Acquisition Fee: </label>
<input type="number" name="acq_fee" value="1">
Here is my JavaScript:
var salesPrice = document.getElementsByName("sales_price")[0];
var incentives = document.getElementsByName("incentives")[0];
var acqFee = document.getElementsByName("acq_fee")[0];
var netCapCost = salesPrice.value - incentives.value + acqFee.value;
I wanted a simple calculation to be done: (3-2+1) = 2. However, netCapCost returns 11, which is the concatenation of the result of (3-2) and 1. What did I do wrong? Many Thanks in advance!
You need to convert those values into numbers with parseInt() or else the + operator will be interpreted as string concatenation. You are doing
var netCapCost = salesPrice.value - incentives.value + acqFee.value;
Which is
var netCapCost = "3" - "2" + "1"
"3"-"2" will return 1, which is what you want but 1 + "1" will be concatenated into "11" since the right operand is a string. So Number + String -> concatenation
var salesPrice;
var incentives;
var acqFee;
var npc;
function calculate(e) {
var netCapCost = (parseFloat(salesPrice.value) - parseFloat(incentives.value) + parseFloat(acqFee.value)).toPrecision(3);
npc.value = netCapCost;
}
window.onload = function (){
salesPrice = document.getElementsByName("sales_price")[0];
incentives = document.getElementsByName("incentives")[0];
acqFee = document.getElementsByName("acq_fee")[0];
npc = document.getElementsByName("npc")[0];
salesPrice.onchange = calculate;
calculate();
};
Your problem is that text fields value is always of type STRING. When subtracting it forces a conversion to type FLOAT. Then the plus operation shares an opperator with the concatenate operation. So when you have two strings being added it concatenates rather than converting to FLOAT or INT. So basically you have "2"-"1" being converted to 2-1 as strings cannot be subtracted which gives you (1) then you have (1)+"1" which will concatenate rather than add as you have a string. Always use parseFloat or parseInt when expecting numeric data from user entry as it will always be a string when originally submitted.
you are doing a string concatation, all value get from input value are string,
the first calcuation salesPrice.value - incentives.value is currect is becuase, the - sign convert the incentives.value to number
the currect way is
var netCapCost = parseInt(salesPrice.value, 10) - parseInt(incentives.value, 10) + parseInt(acqFee.value, 10);
it's better to use a Math library to do the calcuation in javascript, because sooner or later, you will encounter the problem like 0.3 - 0.2 = 0.09999999
I think confusion here is HTML 5 introduces input type number however javascript engine doesn't introduce support for reading such specific fields. We end up using old traditional way of reading input field value which defaults everything to string.
Only advantage of using number type field would be that you do not have to worry about exception/erroneous situation where number is not being entered.
Other answer suggesting to use parseInt function, is the way to go unless you have luxury of introducing javascript framework like jQuery and use more sophisticated approach for reading it.
Hello Stackoverflow people,
My question is how to change a variable I assigned with JavaScript using the value of an HTML input tag.
my progress:
<script type="text/javascript">
var x = 0;
document.write(x);
function addtox() {
var addx = document.getElementById("plusx").value;
x = x + addx;
}
</script>
<input id="plusx" type="number">
<input type="button" onclick="addtox()" value="add">
The result is that it literally adds the value of id="plusx" to the 0 that's already there. So if the input would be 50, it would return 050, and not 50. If I repeat the button it returns 05050 in stead of 100.
How can I fix this?
Also: how can I update text that is already writting to the screen? x is already written to the screenbefore the change and doesn't update after it is assigned a new value.
p.s
Sorry if I am a bit vague, not too familiar with coding questions like mine.
The value of an input element is a string type. You need to convert it to an integer:
x += parseInt(document.getElementById("plusx"), 10);
The return value from dom lookup is string. And so the result you are getting is string concatenation. Convert the return from dom lookup to integer using the parseInt () function. Then you should get the correct answer.
You can just put
X = "0" + addx;
This way you will always have the 0
- this will work if you just want to place a 0 In front.
if you want a more simple way of converting to integer just times your value by 1 will convert the strings to numbers.
So add in x = 0 * 1
And x= x + addx * 1
This will just give you your result without a 0 in front.
If you want 0 in front and number do
X = "0" + addx * 1;