I want to pass in a value, obtained from the an html object, convert that value into an integer so I can run arithmetic on it before outputting it. As my code stands now, it just adds them up like a string. So a value of 5 + a modifier of 100 ends up equaling = 5100, not 105.
Here's my form code:
<form>
Add Amount: <select id="addTweets">
<option value=5>5</option>
<option value=10>10</option>
<option value=15>15</option>
</select>
</br>
<input type="button" value="Add It" onclick="addTweet()" />
</form>
Here's my script:
function addTweet()
{
var mod = 100;
var results = document.getElementById("addTweets").value;
results += mod;
document.getElementById("tweetsOutput").innerHTML = results;
}
The unary plus (+) coerces its operand into a number:
var results = +document.getElementById("addTweets").value;
...
typeof( results ); // number
Use parseInt:
var results = document.getElementById("addTweets").value;
var intResults = parseInt(results, 10) + mod;
You can use parseInt
var results = parseInt(document.getElementById("addTweets").value);
just add parseInt, then you could add it normally
var results = parseInt(document.getElementById("addTweets").value);
EDIT:
parseInt alternate, you can use "|0" use bitwise-or zero
var results = document.getElementById("addTweets").value|0;
Try:
var valResult = document.getElementById("addTweets").value; // get the value of the field
var results = parseInt(valResult) + mod; // convert the value to int to do calculation
document.getElementById("addTweets").value = results; // assign results to the field value
Generally, you can convert the string numerical values into integers by doing a mathematical operation on it:
x = "9"; //String numerical value
y = 10;//integer value
alert(x+y)// output 910;
x = x*1;
alert(x+y) // output 19
Checkout this demo
$("#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
});
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.
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.
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;